1 /****************************************************************************
2 **
3 ** Copyright (C) 2017 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Marc Mutz <marc.mutz@kdab.com>
4 ** Copyright (C) 2019 Mail.ru Group.
5 ** Contact: http://www.qt.io/licensing/
6 **
7 ** This file is part of the QtCore module of the Qt Toolkit.
8 **
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** Commercial License Usage
11 ** Licensees holding valid commercial Qt licenses may use this file in
12 ** accordance with the commercial license agreement provided with the
13 ** Software or, alternatively, in accordance with the terms contained in
14 ** a written agreement between you and The Qt Company. For licensing terms
15 ** and conditions see https://www.qt.io/terms-conditions. For further
16 ** information use the contact form at https://www.qt.io/contact-us.
17 **
18 ** GNU Lesser General Public License Usage
19 ** Alternatively, this file may be used under the terms of the GNU Lesser
20 ** General Public License version 3 as published by the Free Software
21 ** Foundation and appearing in the file LICENSE.LGPL3 included in the
22 ** packaging of this file. Please review the following information to
23 ** ensure the GNU Lesser General Public License version 3 requirements
24 ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
25 **
26 ** GNU General Public License Usage
27 ** Alternatively, this file may be used under the terms of the GNU
28 ** General Public License version 2.0 or (at your option) the GNU General
29 ** Public license version 3 or any later version approved by the KDE Free
30 ** Qt Foundation. The licenses are as published by the Free Software
31 ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
32 ** included in the packaging of this file. Please review the following
33 ** information to ensure the GNU General Public License requirements will
34 ** be met: https://www.gnu.org/licenses/gpl-2.0.html and
35 ** https://www.gnu.org/licenses/gpl-3.0.html.
36 **
37 ** $QT_END_LICENSE$
38 **
39 ****************************************************************************/
40 #ifndef QSTRINGVIEW_H
41 #define QSTRINGVIEW_H
42 
43 #ifndef QT_STRINGVIEW_LEVEL
44 #  define QT_STRINGVIEW_LEVEL 1
45 #endif
46 
47 #include <QtCore/qchar.h>
48 #include <QtCore/qbytearray.h>
49 #include <QtCore/qstringliteral.h>
50 #include <QtCore/qstringalgorithms.h>
51 
52 #include <string>
53 
54 QT_BEGIN_NAMESPACE
55 
56 class QString;
57 class QStringRef;
58 class QRegularExpression;
59 
60 namespace QtPrivate {
61 template <typename Char>
62 struct IsCompatibleCharTypeHelper
63     : std::integral_constant<bool,
64                              std::is_same<Char, QChar>::value ||
65                              std::is_same<Char, ushort>::value ||
66                              std::is_same<Char, char16_t>::value ||
67                              (std::is_same<Char, wchar_t>::value && sizeof(wchar_t) == sizeof(QChar))> {};
68 template <typename Char>
69 struct IsCompatibleCharType
70     : IsCompatibleCharTypeHelper<typename std::remove_cv<typename std::remove_reference<Char>::type>::type> {};
71 
72 template <typename Array>
73 struct IsCompatibleArrayHelper : std::false_type {};
74 template <typename Char, size_t N>
75 struct IsCompatibleArrayHelper<Char[N]>
76     : IsCompatibleCharType<Char> {};
77 template <typename Array>
78 struct IsCompatibleArray
79     : IsCompatibleArrayHelper<typename std::remove_cv<typename std::remove_reference<Array>::type>::type> {};
80 
81 template <typename Pointer>
82 struct IsCompatiblePointerHelper : std::false_type {};
83 template <typename Char>
84 struct IsCompatiblePointerHelper<Char*>
85     : IsCompatibleCharType<Char> {};
86 template <typename Pointer>
87 struct IsCompatiblePointer
88     : IsCompatiblePointerHelper<typename std::remove_cv<typename std::remove_reference<Pointer>::type>::type> {};
89 
90 template <typename T>
91 struct IsCompatibleStdBasicStringHelper : std::false_type {};
92 template <typename Char, typename...Args>
93 struct IsCompatibleStdBasicStringHelper<std::basic_string<Char, Args...> >
94     : IsCompatibleCharType<Char> {};
95 
96 template <typename T>
97 struct IsCompatibleStdBasicString
98     : IsCompatibleStdBasicStringHelper<
99         typename std::remove_cv<typename std::remove_reference<T>::type>::type
100       > {};
101 
102 } // namespace QtPrivate
103 
104 class QStringView
105 {
106 public:
107     typedef char16_t storage_type;
108     typedef const QChar value_type;
109     typedef std::ptrdiff_t difference_type;
110     typedef qsizetype size_type;
111     typedef value_type &reference;
112     typedef value_type &const_reference;
113     typedef value_type *pointer;
114     typedef value_type *const_pointer;
115 
116     typedef pointer iterator;
117     typedef const_pointer const_iterator;
118     typedef std::reverse_iterator<iterator> reverse_iterator;
119     typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
120 
121 private:
122     template <typename Char>
123     using if_compatible_char = typename std::enable_if<QtPrivate::IsCompatibleCharType<Char>::value, bool>::type;
124 
125     template <typename Array>
126     using if_compatible_array = typename std::enable_if<QtPrivate::IsCompatibleArray<Array>::value, bool>::type;
127 
128     template <typename Pointer>
129     using if_compatible_pointer = typename std::enable_if<QtPrivate::IsCompatiblePointer<Pointer>::value, bool>::type;
130 
131     template <typename T>
132     using if_compatible_string = typename std::enable_if<QtPrivate::IsCompatibleStdBasicString<T>::value, bool>::type;
133 
134     template <typename T>
135     using if_compatible_qstring_like = typename std::enable_if<std::is_same<T, QString>::value || std::is_same<T, QStringRef>::value, bool>::type;
136 
137     template <typename Char, size_t N>
138     static Q_DECL_CONSTEXPR qsizetype lengthHelperArray(const Char (&)[N]) noexcept
139     {
140         return qsizetype(N - 1);
141     }
142 
143     template <typename Char>
144     static qsizetype lengthHelperPointer(const Char *str) noexcept
145     {
146 #if defined(Q_CC_GNU) && !defined(Q_CC_CLANG) && !defined(Q_CC_INTEL)
147         if (__builtin_constant_p(*str)) {
148             qsizetype result = 0;
149             while (*str++)
150                 ++result;
151             return result;
152         }
153 #endif
154         return QtPrivate::qustrlen(reinterpret_cast<const ushort *>(str));
155     }
156     static qsizetype lengthHelperPointer(const QChar *str) noexcept
157     {
158         return QtPrivate::qustrlen(reinterpret_cast<const ushort *>(str));
159     }
160 
161     template <typename Char>
162     static const storage_type *castHelper(const Char *str) noexcept
163     { return reinterpret_cast<const storage_type*>(str); }
164     static Q_DECL_CONSTEXPR const storage_type *castHelper(const storage_type *str) noexcept
165     { return str; }
166 
167 public:
168     Q_DECL_CONSTEXPR QStringView() noexcept
169         : m_size(0), m_data(nullptr) {}
170     Q_DECL_CONSTEXPR QStringView(std::nullptr_t) noexcept
171         : QStringView() {}
172 
173     template <typename Char, if_compatible_char<Char> = true>
174     Q_DECL_CONSTEXPR QStringView(const Char *str, qsizetype len)
175         : m_size((Q_ASSERT(len >= 0), Q_ASSERT(str || !len), len)),
176           m_data(castHelper(str)) {}
177 
178     template <typename Char, if_compatible_char<Char> = true>
179     Q_DECL_CONSTEXPR QStringView(const Char *f, const Char *l)
180         : QStringView(f, l - f) {}
181 
182 #ifdef Q_CLANG_QDOC
183     template <typename Char, size_t N>
184     Q_DECL_CONSTEXPR QStringView(const Char (&array)[N]) noexcept;
185 
186     template <typename Char>
187     Q_DECL_CONSTEXPR QStringView(const Char *str) noexcept;
188 #else
189 #if QT_DEPRECATED_SINCE(5, 14)
190     template <typename Array, if_compatible_array<Array> = true>
191     QT_DEPRECATED_VERSION_X_5_14(R"(Use u"~~~" or QStringView(u"~~~") instead of QStringViewLiteral("~~~"))")
192     Q_DECL_CONSTEXPR QStringView(const Array &str, QtPrivate::Deprecated_t) noexcept
193         : QStringView(str, lengthHelperArray(str)) {}
194 #endif // QT_DEPRECATED_SINCE
195 
196     template <typename Array, if_compatible_array<Array> = true>
197     Q_DECL_CONSTEXPR QStringView(const Array &str) noexcept
198         : QStringView(str, lengthHelperArray(str)) {}
199 
200     template <typename Pointer, if_compatible_pointer<Pointer> = true>
201     Q_DECL_CONSTEXPR QStringView(const Pointer &str) noexcept
202         : QStringView(str, str ? lengthHelperPointer(str) : 0) {}
203 #endif
204 
205 #ifdef Q_CLANG_QDOC
206     QStringView(const QString &str) noexcept;
207     QStringView(const QStringRef &str) noexcept;
208 #else
209     template <typename String, if_compatible_qstring_like<String> = true>
210     QStringView(const String &str) noexcept
211         : QStringView(str.isNull() ? nullptr : str.data(), qsizetype(str.size())) {}
212 #endif
213 
214     template <typename StdBasicString, if_compatible_string<StdBasicString> = true>
215     Q_DECL_CONSTEXPR QStringView(const StdBasicString &str) noexcept
216         : QStringView(str.data(), qsizetype(str.size())) {}
217 
218     Q_REQUIRED_RESULT inline QString toString() const; // defined in qstring.h
219 
220     Q_REQUIRED_RESULT Q_DECL_CONSTEXPR qsizetype size() const noexcept { return m_size; }
221     Q_REQUIRED_RESULT const_pointer data() const noexcept { return reinterpret_cast<const_pointer>(m_data); }
222     Q_REQUIRED_RESULT Q_DECL_CONSTEXPR const storage_type *utf16() const noexcept { return m_data; }
223 
224     Q_REQUIRED_RESULT Q_DECL_CONSTEXPR QChar operator[](qsizetype n) const
225     { return Q_ASSERT(n >= 0), Q_ASSERT(n < size()), QChar(m_data[n]); }
226 
227     //
228     // QString API
229     //
230 
231     template <typename...Args>
232     Q_REQUIRED_RESULT inline QString arg(Args &&...args) const; // defined in qstring.h
233 
234     Q_REQUIRED_RESULT QByteArray toLatin1() const { return QtPrivate::convertToLatin1(*this); }
235     Q_REQUIRED_RESULT QByteArray toUtf8() const { return QtPrivate::convertToUtf8(*this); }
236     Q_REQUIRED_RESULT QByteArray toLocal8Bit() const { return QtPrivate::convertToLocal8Bit(*this); }
237     Q_REQUIRED_RESULT inline QVector<uint> toUcs4() const; // defined in qvector.h
238 
239     Q_REQUIRED_RESULT Q_DECL_CONSTEXPR QChar at(qsizetype n) const { return (*this)[n]; }
240 
241     Q_REQUIRED_RESULT Q_DECL_CONSTEXPR QStringView mid(qsizetype pos) const
242     {
243         return QStringView(m_data + qBound(qsizetype(0), pos, m_size), m_size - qBound(qsizetype(0), pos, m_size));
244     }
245     Q_REQUIRED_RESULT Q_DECL_CONSTEXPR QStringView mid(qsizetype pos, qsizetype n) const
246     {
247         return QStringView(m_data + qBound(qsizetype(0), pos, m_size), qBound(qsizetype(0), pos + n, m_size) - qBound(qsizetype(0), pos, m_size));
248     }
249     Q_REQUIRED_RESULT Q_DECL_CONSTEXPR QStringView left(qsizetype n) const
250     {
251         return QStringView(m_data, (size_t(n) > size_t(m_size) ? m_size : n));
252     }
253     Q_REQUIRED_RESULT Q_DECL_CONSTEXPR QStringView right(qsizetype n) const
254     {
255         return QStringView(m_data + m_size - (size_t(n) > size_t(m_size) ? m_size : n), (size_t(n) > size_t(m_size) ? m_size : n));
256     }
257     Q_REQUIRED_RESULT Q_DECL_CONSTEXPR QStringView chopped(qsizetype n) const
258     { return Q_ASSERT(n >= 0), Q_ASSERT(n <= size()), QStringView(m_data, m_size - n); }
259 
260     Q_DECL_RELAXED_CONSTEXPR void truncate(qsizetype n)
261     { Q_ASSERT(n >= 0); Q_ASSERT(n <= size()); m_size = n; }
262     Q_DECL_RELAXED_CONSTEXPR void chop(qsizetype n)
263     { Q_ASSERT(n >= 0); Q_ASSERT(n <= size()); m_size -= n; }
264 
265     Q_REQUIRED_RESULT QStringView trimmed() const noexcept { return QtPrivate::trimmed(*this); }
266 
267     Q_REQUIRED_RESULT int compare(QStringView other, Qt::CaseSensitivity cs = Qt::CaseSensitive) const noexcept
268     { return QtPrivate::compareStrings(*this, other, cs); }
269     Q_REQUIRED_RESULT inline int compare(QLatin1String other, Qt::CaseSensitivity cs = Qt::CaseSensitive) const noexcept;
270     Q_REQUIRED_RESULT Q_DECL_CONSTEXPR int compare(QChar c) const noexcept
271     { return size() >= 1 ? compare_single_char_helper(*utf16() - c.unicode()) : -1; }
272     Q_REQUIRED_RESULT int compare(QChar c, Qt::CaseSensitivity cs) const noexcept
273     { return QtPrivate::compareStrings(*this, QStringView(&c, 1), cs); }
274 
275     Q_REQUIRED_RESULT bool startsWith(QStringView s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const noexcept
276     { return QtPrivate::startsWith(*this, s, cs); }
277     Q_REQUIRED_RESULT inline bool startsWith(QLatin1String s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const noexcept;
278     Q_REQUIRED_RESULT bool startsWith(QChar c) const noexcept
279     { return !empty() && front() == c; }
280     Q_REQUIRED_RESULT bool startsWith(QChar c, Qt::CaseSensitivity cs) const noexcept
281     { return QtPrivate::startsWith(*this, QStringView(&c, 1), cs); }
282 
283     Q_REQUIRED_RESULT bool endsWith(QStringView s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const noexcept
284     { return QtPrivate::endsWith(*this, s, cs); }
285     Q_REQUIRED_RESULT inline bool endsWith(QLatin1String s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const noexcept;
286     Q_REQUIRED_RESULT bool endsWith(QChar c) const noexcept
287     { return !empty() && back() == c; }
288     Q_REQUIRED_RESULT bool endsWith(QChar c, Qt::CaseSensitivity cs) const noexcept
289     { return QtPrivate::endsWith(*this, QStringView(&c, 1), cs); }
290 
291     Q_REQUIRED_RESULT qsizetype indexOf(QChar c, qsizetype from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive) const noexcept
292     { return QtPrivate::findString(*this, from, QStringView(&c, 1), cs); }
293     Q_REQUIRED_RESULT qsizetype indexOf(QStringView s, qsizetype from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive) const noexcept
294     { return QtPrivate::findString(*this, from, s, cs); }
295     Q_REQUIRED_RESULT inline qsizetype indexOf(QLatin1String s, qsizetype from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive) const noexcept;
296 
297     Q_REQUIRED_RESULT bool contains(QChar c, Qt::CaseSensitivity cs = Qt::CaseSensitive) const noexcept
298     { return indexOf(QStringView(&c, 1), 0, cs) != qsizetype(-1); }
299     Q_REQUIRED_RESULT bool contains(QStringView s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const noexcept
300     { return indexOf(s, 0, cs) != qsizetype(-1); }
301     Q_REQUIRED_RESULT inline bool contains(QLatin1String s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const noexcept;
302 
303     Q_REQUIRED_RESULT inline qsizetype count(QChar c, Qt::CaseSensitivity cs = Qt::CaseSensitive) const noexcept;
304     Q_REQUIRED_RESULT inline qsizetype count(QStringView s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const noexcept;
305 
306     Q_REQUIRED_RESULT qsizetype lastIndexOf(QChar c, qsizetype from = -1, Qt::CaseSensitivity cs = Qt::CaseSensitive) const noexcept
307     { return QtPrivate::lastIndexOf(*this, from, QStringView(&c, 1), cs); }
308     Q_REQUIRED_RESULT qsizetype lastIndexOf(QStringView s, qsizetype from = -1, Qt::CaseSensitivity cs = Qt::CaseSensitive) const noexcept
309     { return QtPrivate::lastIndexOf(*this, from, s, cs); }
310     Q_REQUIRED_RESULT inline qsizetype lastIndexOf(QLatin1String s, qsizetype from = -1, Qt::CaseSensitivity cs = Qt::CaseSensitive) const noexcept;
311 
312     Q_REQUIRED_RESULT bool isRightToLeft() const noexcept
313     { return QtPrivate::isRightToLeft(*this); }
314     Q_REQUIRED_RESULT bool isValidUtf16() const noexcept
315     { return QtPrivate::isValidUtf16(*this); }
316 
317     Q_REQUIRED_RESULT inline short toShort(bool *ok = nullptr, int base = 10) const;
318     Q_REQUIRED_RESULT inline ushort toUShort(bool *ok = nullptr, int base = 10) const;
319     Q_REQUIRED_RESULT inline int toInt(bool *ok = nullptr, int base = 10) const;
320     Q_REQUIRED_RESULT inline uint toUInt(bool *ok = nullptr, int base = 10) const;
321     Q_REQUIRED_RESULT inline long toLong(bool *ok = nullptr, int base = 10) const;
322     Q_REQUIRED_RESULT inline ulong toULong(bool *ok = nullptr, int base = 10) const;
323     Q_REQUIRED_RESULT inline qlonglong toLongLong(bool *ok = nullptr, int base = 10) const;
324     Q_REQUIRED_RESULT inline qulonglong toULongLong(bool *ok = nullptr, int base = 10) const;
325     Q_REQUIRED_RESULT inline float toFloat(bool *ok = nullptr) const;
326     Q_REQUIRED_RESULT inline double toDouble(bool *ok = nullptr) const;
327 
328     Q_REQUIRED_RESULT inline int toWCharArray(wchar_t *array) const; // defined in qstring.h
329 
330     Q_REQUIRED_RESULT inline
331     QList<QStringView> split(QStringView sep,
332                              Qt::SplitBehavior behavior = Qt::KeepEmptyParts,
333                              Qt::CaseSensitivity cs = Qt::CaseSensitive) const;
334     Q_REQUIRED_RESULT inline
335     QList<QStringView> split(QChar sep, Qt::SplitBehavior behavior = Qt::KeepEmptyParts,
336                              Qt::CaseSensitivity cs = Qt::CaseSensitive) const;
337 
338 #if QT_CONFIG(regularexpression)
339     Q_REQUIRED_RESULT inline
340     QList<QStringView> split(const QRegularExpression &sep, Qt::SplitBehavior behavior = Qt::KeepEmptyParts) const;
341 #endif
342 
343     //
344     // STL compatibility API:
345     //
346     Q_REQUIRED_RESULT const_iterator begin()   const noexcept { return data(); }
347     Q_REQUIRED_RESULT const_iterator end()     const noexcept { return data() + size(); }
348     Q_REQUIRED_RESULT const_iterator cbegin()  const noexcept { return begin(); }
349     Q_REQUIRED_RESULT const_iterator cend()    const noexcept { return end(); }
350     Q_REQUIRED_RESULT const_reverse_iterator rbegin()  const noexcept { return const_reverse_iterator(end()); }
351     Q_REQUIRED_RESULT const_reverse_iterator rend()    const noexcept { return const_reverse_iterator(begin()); }
352     Q_REQUIRED_RESULT const_reverse_iterator crbegin() const noexcept { return rbegin(); }
353     Q_REQUIRED_RESULT const_reverse_iterator crend()   const noexcept { return rend(); }
354 
355     Q_REQUIRED_RESULT Q_DECL_CONSTEXPR bool empty() const noexcept { return size() == 0; }
356     Q_REQUIRED_RESULT Q_DECL_CONSTEXPR QChar front() const { return Q_ASSERT(!empty()), QChar(m_data[0]); }
357     Q_REQUIRED_RESULT Q_DECL_CONSTEXPR QChar back()  const { return Q_ASSERT(!empty()), QChar(m_data[m_size - 1]); }
358 
359     //
360     // Qt compatibility API:
361     //
362     Q_REQUIRED_RESULT Q_DECL_CONSTEXPR bool isNull() const noexcept { return !m_data; }
363     Q_REQUIRED_RESULT Q_DECL_CONSTEXPR bool isEmpty() const noexcept { return empty(); }
364     Q_REQUIRED_RESULT Q_DECL_CONSTEXPR int length() const /* not nothrow! */
365     { return Q_ASSERT(int(size()) == size()), int(size()); }
366     Q_REQUIRED_RESULT Q_DECL_CONSTEXPR QChar first() const { return front(); }
367     Q_REQUIRED_RESULT Q_DECL_CONSTEXPR QChar last()  const { return back(); }
368 private:
369     qsizetype m_size;
370     const storage_type *m_data;
371 
372     Q_DECL_CONSTEXPR int compare_single_char_helper(int diff) const noexcept
373     { return diff ? diff : size() > 1 ? 1 : 0; }
374 };
375 Q_DECLARE_TYPEINFO(QStringView, Q_PRIMITIVE_TYPE);
376 
377 template <typename QStringLike, typename std::enable_if<
378     std::is_same<QStringLike, QString>::value || std::is_same<QStringLike, QStringRef>::value,
379     bool>::type = true>
380 inline QStringView qToStringViewIgnoringNull(const QStringLike &s) noexcept
381 { return QStringView(s.data(), s.size()); }
382 
383 QT_END_NAMESPACE
384 
385 #endif /* QSTRINGVIEW_H */
386