1/****************************************************************************
2**
3** Copyright (C) 2020 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/*
44 This macro enables three "levels" of QStringView support:
45
46 1. offer QStringView, overload some functions taking QString with
47 QStringView
48
49 2. Obsolete: QStringRef and its overloads have been removed.
50
51 3. like 2, but replace functions taking QString, too.
52*/
53#ifndef QT_STRINGVIEW_LEVEL
54# define QT_STRINGVIEW_LEVEL 1
55#endif
56
57#include <QtCore/qchar.h>
58#include <QtCore/qbytearray.h>
59#include <QtCore/qstringliteral.h>
60#include <QtCore/qstringalgorithms.h>
61
62#include <string>
63
64#if defined(Q_OS_DARWIN) || defined(Q_QDOC)
65Q_FORWARD_DECLARE_CF_TYPE(CFString);
66Q_FORWARD_DECLARE_OBJC_CLASS(NSString);
67#endif
68
69QT_BEGIN_NAMESPACE
70
71class QString;
72class QStringView;
73class QRegularExpression;
74
75namespace QtPrivate {
76template <typename Char>
77struct IsCompatibleCharTypeHelper
78 : std::integral_constant<bool,
79 std::is_same<Char, QChar>::value ||
80 std::is_same<Char, ushort>::value ||
81 std::is_same<Char, char16_t>::value ||
82 (std::is_same<Char, wchar_t>::value && sizeof(wchar_t) == sizeof(QChar))> {};
83template <typename Char>
84struct IsCompatibleCharType
85 : IsCompatibleCharTypeHelper<typename std::remove_cv<typename std::remove_reference<Char>::type>::type> {};
86
87template <typename Pointer>
88struct IsCompatiblePointerHelper : std::false_type {};
89template <typename Char>
90struct IsCompatiblePointerHelper<Char*>
91 : IsCompatibleCharType<Char> {};
92template <typename Pointer>
93struct IsCompatiblePointer
94 : IsCompatiblePointerHelper<typename std::remove_cv<typename std::remove_reference<Pointer>::type>::type> {};
95
96template <typename T, typename Enable = void>
97struct IsContainerCompatibleWithQStringView : std::false_type {};
98
99template <typename T>
100struct IsContainerCompatibleWithQStringView<T, std::enable_if_t<std::conjunction_v<
101 // lacking concepts and ranges, we accept any T whose std::data yields a suitable pointer ...
102 IsCompatiblePointer<decltype( std::data(std::declval<const T &>()) )>,
103 // ... and that has a suitable size ...
104 std::is_convertible<decltype( std::size(std::declval<const T &>()) ), qsizetype>,
105 // ... and it's a range as it defines an iterator-like API
106 IsCompatibleCharType<typename std::iterator_traits<decltype( std::begin(std::declval<const T &>()) )>::value_type>,
107 std::is_convertible<
108 decltype( std::begin(std::declval<const T &>()) != std::end(std::declval<const T &>()) ),
109 bool>,
110
111 // These need to be treated specially due to the empty vs null distinction
112 std::negation<std::is_same<std::decay_t<T>, QString>>,
113
114 // Don't make an accidental copy constructor
115 std::negation<std::is_same<std::decay_t<T>, QStringView>>
116 >>> : std::true_type {};
117
118} // namespace QtPrivate
119
120class QStringView
121{
122public:
123 typedef char16_t storage_type;
124 typedef const QChar value_type;
125 typedef std::ptrdiff_t difference_type;
126 typedef qsizetype size_type;
127 typedef value_type &reference;
128 typedef value_type &const_reference;
129 typedef value_type *pointer;
130 typedef value_type *const_pointer;
131
132 typedef pointer iterator;
133 typedef const_pointer const_iterator;
134 typedef std::reverse_iterator<iterator> reverse_iterator;
135 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
136
137private:
138 template <typename Char>
139 using if_compatible_char = typename std::enable_if<QtPrivate::IsCompatibleCharType<Char>::value, bool>::type;
140
141 template <typename Pointer>
142 using if_compatible_pointer = typename std::enable_if<QtPrivate::IsCompatiblePointer<Pointer>::value, bool>::type;
143
144 template <typename T>
145 using if_compatible_qstring_like = typename std::enable_if<std::is_same<T, QString>::value, bool>::type;
146
147 template <typename T>
148 using if_compatible_container = typename std::enable_if<QtPrivate::IsContainerCompatibleWithQStringView<T>::value, bool>::type;
149
150 template <typename Char>
151 static qsizetype lengthHelperPointer(const Char *str) noexcept
152 {
153#if defined(__cpp_lib_is_constant_evaluated)
154 if (std::is_constant_evaluated())
155 return std::char_traits<Char>::length(str);
156#elif defined(Q_CC_GNU) && !defined(Q_CC_CLANG) && !defined(Q_CC_INTEL)
157 if (__builtin_constant_p(*str))
158 return std::char_traits<Char>::length(str);
159#endif
160 return QtPrivate::qustrlen(reinterpret_cast<const char16_t *>(str));
161 }
162 static qsizetype lengthHelperPointer(const QChar *str) noexcept
163 {
164 return QtPrivate::qustrlen(reinterpret_cast<const char16_t *>(str));
165 }
166
167 template <typename Container>
168 static constexpr qsizetype lengthHelperContainer(const Container &c) noexcept
169 {
170 return qsizetype(std::size(c));
171 }
172
173 template <typename Char, size_t N>
174 static constexpr qsizetype lengthHelperContainer(const Char (&str)[N]) noexcept
175 {
176 const auto it = std::char_traits<Char>::find(str, N, Char(0));
177 const auto end = it ? it : std::end(str);
178 return qsizetype(std::distance(str, end));
179 }
180
181 template <typename Char>
182 static const storage_type *castHelper(const Char *str) noexcept
183 { return reinterpret_cast<const storage_type*>(str); }
184 static constexpr const storage_type *castHelper(const storage_type *str) noexcept
185 { return str; }
186
187public:
188 constexpr QStringView() noexcept
189 : m_size(0), m_data(nullptr) {}
190 constexpr QStringView(std::nullptr_t) noexcept
191 : QStringView() {}
192
193 template <typename Char, if_compatible_char<Char> = true>
194 constexpr QStringView(const Char *str, qsizetype len)
195 : m_size((Q_ASSERT(len >= 0), Q_ASSERT(str || !len), len)),
196 m_data(castHelper(str)) {}
197
198 template <typename Char, if_compatible_char<Char> = true>
199 constexpr QStringView(const Char *f, const Char *l)
200 : QStringView(f, l - f) {}
201
202#ifdef Q_CLANG_QDOC
203 template <typename Char, size_t N>
204 constexpr QStringView(const Char (&array)[N]) noexcept;
205
206 template <typename Char>
207 constexpr QStringView(const Char *str) noexcept;
208#else
209
210 template <typename Pointer, if_compatible_pointer<Pointer> = true>
211 constexpr QStringView(const Pointer &str) noexcept
212 : QStringView(str, str ? lengthHelperPointer(str) : 0) {}
213#endif
214
215#ifdef Q_CLANG_QDOC
216 QStringView(const QString &str) noexcept;
217#else
218 template <typename String, if_compatible_qstring_like<String> = true>
219 QStringView(const String &str) noexcept
220 : QStringView(str.isNull() ? nullptr : str.data(), qsizetype(str.size())) {}
221#endif
222
223 template <typename Container, if_compatible_container<Container> = true>
224 constexpr QStringView(const Container &c) noexcept
225 : QStringView(std::data(c), lengthHelperContainer(c)) {}
226
227 template <typename Char, size_t Size, if_compatible_char<Char> = true>
228 [[nodiscard]] constexpr static QStringView fromArray(const Char (&string)[Size]) noexcept
229 { return QStringView(string, Size); }
230
231 [[nodiscard]] inline QString toString() const; // defined in qstring.h
232#if defined(Q_OS_DARWIN) || defined(Q_QDOC)
233 // defined in qcore_foundation.mm
234 [[nodiscard]] Q_CORE_EXPORT CFStringRef toCFString() const Q_DECL_CF_RETURNS_RETAINED;
235 [[nodiscard]] Q_CORE_EXPORT NSString *toNSString() const Q_DECL_NS_RETURNS_AUTORELEASED;
236#endif
237
238 [[nodiscard]] constexpr qsizetype size() const noexcept { return m_size; }
239 [[nodiscard]] const_pointer data() const noexcept { return reinterpret_cast<const_pointer>(m_data); }
240 [[nodiscard]] const_pointer constData() const noexcept { return data(); }
241 [[nodiscard]] constexpr const storage_type *utf16() const noexcept { return m_data; }
242
243 [[nodiscard]] constexpr QChar operator[](qsizetype n) const
244 { return Q_ASSERT(n >= 0), Q_ASSERT(n < size()), QChar(m_data[n]); }
245
246 //
247 // QString API
248 //
249
250 template <typename...Args>
251 [[nodiscard]] inline QString arg(Args &&...args) const; // defined in qstring.h
252
253 [[nodiscard]] QByteArray toLatin1() const { return QtPrivate::convertToLatin1(*this); }
254 [[nodiscard]] QByteArray toUtf8() const { return QtPrivate::convertToUtf8(*this); }
255 [[nodiscard]] QByteArray toLocal8Bit() const { return QtPrivate::convertToLocal8Bit(*this); }
256 [[nodiscard]] inline QList<uint> toUcs4() const; // defined in qlist.h
257
258 [[nodiscard]] constexpr QChar at(qsizetype n) const { return (*this)[n]; }
259
260 [[nodiscard]] constexpr QStringView mid(qsizetype pos, qsizetype n = -1) const
261 {
262 using namespace QtPrivate;
263 auto result = QContainerImplHelper::mid(size(), &pos, &n);
264 return result == QContainerImplHelper::Null ? QStringView() : QStringView(m_data + pos, n);
265 }
266 [[nodiscard]] constexpr QStringView left(qsizetype n) const
267 {
268 if (size_t(n) >= size_t(size()))
269 n = size();
270 return QStringView(m_data, n);
271 }
272 [[nodiscard]] constexpr QStringView right(qsizetype n) const
273 {
274 if (size_t(n) >= size_t(size()))
275 n = size();
276 return QStringView(m_data + m_size - n, n);
277 }
278
279 [[nodiscard]] constexpr QStringView first(qsizetype n) const
280 { Q_ASSERT(n >= 0); Q_ASSERT(n <= size()); return QStringView(m_data, n); }
281 [[nodiscard]] constexpr QStringView last(qsizetype n) const
282 { Q_ASSERT(n >= 0); Q_ASSERT(n <= size()); return QStringView(m_data + size() - n, n); }
283 [[nodiscard]] constexpr QStringView sliced(qsizetype pos) const
284 { Q_ASSERT(pos >= 0); Q_ASSERT(pos <= size()); return QStringView(m_data + pos, size() - pos); }
285 [[nodiscard]] constexpr QStringView sliced(qsizetype pos, qsizetype n) const
286 { Q_ASSERT(pos >= 0); Q_ASSERT(n >= 0); Q_ASSERT(size_t(pos) + size_t(n) <= size_t(size())); return QStringView(m_data + pos, n); }
287 [[nodiscard]] constexpr QStringView chopped(qsizetype n) const
288 { return Q_ASSERT(n >= 0), Q_ASSERT(n <= size()), QStringView(m_data, m_size - n); }
289
290 constexpr void truncate(qsizetype n)
291 { Q_ASSERT(n >= 0); Q_ASSERT(n <= size()); m_size = n; }
292 constexpr void chop(qsizetype n)
293 { Q_ASSERT(n >= 0); Q_ASSERT(n <= size()); m_size -= n; }
294
295 [[nodiscard]] QStringView trimmed() const noexcept { return QtPrivate::trimmed(*this); }
296
297 template <typename Needle, typename...Flags>
298 [[nodiscard]] constexpr inline auto tokenize(Needle &&needle, Flags...flags) const
299 noexcept(noexcept(qTokenize(std::declval<const QStringView&>(), std::forward<Needle>(needle), flags...)))
300 -> decltype(qTokenize(*this, std::forward<Needle>(needle), flags...))
301 { return qTokenize(*this, std::forward<Needle>(needle), flags...); }
302
303 [[nodiscard]] int compare(QStringView other, Qt::CaseSensitivity cs = Qt::CaseSensitive) const noexcept
304 { return QtPrivate::compareStrings(*this, other, cs); }
305 [[nodiscard]] inline int compare(QLatin1String other, Qt::CaseSensitivity cs = Qt::CaseSensitive) const noexcept;
306 [[nodiscard]] constexpr int compare(QChar c) const noexcept
307 { return size() >= 1 ? compare_single_char_helper(*utf16() - c.unicode()) : -1; }
308 [[nodiscard]] int compare(QChar c, Qt::CaseSensitivity cs) const noexcept
309 { return QtPrivate::compareStrings(*this, QStringView(&c, 1), cs); }
310
311 [[nodiscard]] bool startsWith(QStringView s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const noexcept
312 { return QtPrivate::startsWith(*this, s, cs); }
313 [[nodiscard]] inline bool startsWith(QLatin1String s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const noexcept;
314 [[nodiscard]] bool startsWith(QChar c) const noexcept
315 { return !empty() && front() == c; }
316 [[nodiscard]] bool startsWith(QChar c, Qt::CaseSensitivity cs) const noexcept
317 { return QtPrivate::startsWith(*this, QStringView(&c, 1), cs); }
318
319 [[nodiscard]] bool endsWith(QStringView s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const noexcept
320 { return QtPrivate::endsWith(*this, s, cs); }
321 [[nodiscard]] inline bool endsWith(QLatin1String s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const noexcept;
322 [[nodiscard]] bool endsWith(QChar c) const noexcept
323 { return !empty() && back() == c; }
324 [[nodiscard]] bool endsWith(QChar c, Qt::CaseSensitivity cs) const noexcept
325 { return QtPrivate::endsWith(*this, QStringView(&c, 1), cs); }
326
327 [[nodiscard]] qsizetype indexOf(QChar c, qsizetype from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive) const noexcept
328 { return QtPrivate::findString(*this, from, QStringView(&c, 1), cs); }
329 [[nodiscard]] qsizetype indexOf(QStringView s, qsizetype from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive) const noexcept
330 { return QtPrivate::findString(*this, from, s, cs); }
331 [[nodiscard]] inline qsizetype indexOf(QLatin1String s, qsizetype from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive) const noexcept;
332
333 [[nodiscard]] bool contains(QChar c, Qt::CaseSensitivity cs = Qt::CaseSensitive) const noexcept
334 { return indexOf(QStringView(&c, 1), 0, cs) != qsizetype(-1); }
335 [[nodiscard]] bool contains(QStringView s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const noexcept
336 { return indexOf(s, 0, cs) != qsizetype(-1); }
337 [[nodiscard]] inline bool contains(QLatin1String s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const noexcept;
338
339 [[nodiscard]] qsizetype count(QChar c, Qt::CaseSensitivity cs = Qt::CaseSensitive) const noexcept
340 { return QtPrivate::count(*this, c, cs); }
341 [[nodiscard]] qsizetype count(QStringView s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const noexcept
342 { return QtPrivate::count(*this, s, cs); }
343
344 [[nodiscard]] qsizetype lastIndexOf(QChar c, qsizetype from = -1, Qt::CaseSensitivity cs = Qt::CaseSensitive) const noexcept
345 { return QtPrivate::lastIndexOf(*this, from, QStringView(&c, 1), cs); }
346 [[nodiscard]] qsizetype lastIndexOf(QStringView s, qsizetype from = -1, Qt::CaseSensitivity cs = Qt::CaseSensitive) const noexcept
347 { return QtPrivate::lastIndexOf(*this, from, s, cs); }
348 [[nodiscard]] inline qsizetype lastIndexOf(QLatin1String s, qsizetype from = -1, Qt::CaseSensitivity cs = Qt::CaseSensitive) const noexcept;
349
350 [[nodiscard]] bool isRightToLeft() const noexcept
351 { return QtPrivate::isRightToLeft(*this); }
352 [[nodiscard]] bool isValidUtf16() const noexcept
353 { return QtPrivate::isValidUtf16(*this); }
354
355 [[nodiscard]] inline short toShort(bool *ok = nullptr, int base = 10) const;
356 [[nodiscard]] inline ushort toUShort(bool *ok = nullptr, int base = 10) const;
357 [[nodiscard]] inline int toInt(bool *ok = nullptr, int base = 10) const;
358 [[nodiscard]] inline uint toUInt(bool *ok = nullptr, int base = 10) const;
359 [[nodiscard]] inline long toLong(bool *ok = nullptr, int base = 10) const;
360 [[nodiscard]] inline ulong toULong(bool *ok = nullptr, int base = 10) const;
361 [[nodiscard]] inline qlonglong toLongLong(bool *ok = nullptr, int base = 10) const;
362 [[nodiscard]] inline qulonglong toULongLong(bool *ok = nullptr, int base = 10) const;
363 [[nodiscard]] Q_CORE_EXPORT float toFloat(bool *ok = nullptr) const;
364 [[nodiscard]] Q_CORE_EXPORT double toDouble(bool *ok = nullptr) const;
365
366 [[nodiscard]] inline qsizetype toWCharArray(wchar_t *array) const; // defined in qstring.h
367
368
369 [[nodiscard]] Q_CORE_EXPORT
370 QList<QStringView> split(QStringView sep,
371 Qt::SplitBehavior behavior = Qt::KeepEmptyParts,
372 Qt::CaseSensitivity cs = Qt::CaseSensitive) const;
373 [[nodiscard]] Q_CORE_EXPORT
374 QList<QStringView> split(QChar sep, Qt::SplitBehavior behavior = Qt::KeepEmptyParts,
375 Qt::CaseSensitivity cs = Qt::CaseSensitive) const;
376
377#if QT_CONFIG(regularexpression)
378 [[nodiscard]] Q_CORE_EXPORT
379 QList<QStringView> split(const QRegularExpression &sep,
380 Qt::SplitBehavior behavior = Qt::KeepEmptyParts) const;
381#endif
382
383 //
384 // STL compatibility API:
385 //
386 [[nodiscard]] const_iterator begin() const noexcept { return data(); }
387 [[nodiscard]] const_iterator end() const noexcept { return data() + size(); }
388 [[nodiscard]] const_iterator cbegin() const noexcept { return begin(); }
389 [[nodiscard]] const_iterator cend() const noexcept { return end(); }
390 [[nodiscard]] const_reverse_iterator rbegin() const noexcept { return const_reverse_iterator(end()); }
391 [[nodiscard]] const_reverse_iterator rend() const noexcept { return const_reverse_iterator(begin()); }
392 [[nodiscard]] const_reverse_iterator crbegin() const noexcept { return rbegin(); }
393 [[nodiscard]] const_reverse_iterator crend() const noexcept { return rend(); }
394
395 [[nodiscard]] constexpr bool empty() const noexcept { return size() == 0; }
396 [[nodiscard]] constexpr QChar front() const { return Q_ASSERT(!empty()), QChar(m_data[0]); }
397 [[nodiscard]] constexpr QChar back() const { return Q_ASSERT(!empty()), QChar(m_data[m_size - 1]); }
398
399 //
400 // Qt compatibility API:
401 //
402 [[nodiscard]] constexpr bool isNull() const noexcept { return !m_data; }
403 [[nodiscard]] constexpr bool isEmpty() const noexcept { return empty(); }
404 [[nodiscard]] constexpr int length() const /* not nothrow! */
405 { return Q_ASSERT(int(size()) == size()), int(size()); }
406 [[nodiscard]] constexpr QChar first() const { return front(); }
407 [[nodiscard]] constexpr QChar last() const { return back(); }
408private:
409 qsizetype m_size;
410 const storage_type *m_data;
411
412 constexpr int compare_single_char_helper(int diff) const noexcept
413 { return diff ? diff : size() > 1 ? 1 : 0; }
414};
415Q_DECLARE_TYPEINFO(QStringView, Q_PRIMITIVE_TYPE);
416
417template <typename QStringLike, typename std::enable_if<
418 std::is_same<QStringLike, QString>::value,
419 bool>::type = true>
420inline QStringView qToStringViewIgnoringNull(const QStringLike &s) noexcept
421{ return QStringView(s.data(), s.size()); }
422
423// QChar inline functions:
424
425[[nodiscard]] constexpr auto QChar::fromUcs4(char32_t c) noexcept
426{
427 struct R {
428 char16_t chars[2];
429 [[nodiscard]] constexpr operator QStringView() const noexcept { return {begin(), end()}; }
430 [[nodiscard]] constexpr qsizetype size() const noexcept { return chars[1] ? 2 : 1; }
431 [[nodiscard]] constexpr const char16_t *begin() const noexcept { return chars; }
432 [[nodiscard]] constexpr const char16_t *end() const noexcept { return begin() + size(); }
433 };
434 return requiresSurrogates(c) ? R{{QChar::highSurrogate(c),
435 QChar::lowSurrogate(c)}} :
436 R{{char16_t(c), u'\0'}} ;
437}
438
439QT_END_NAMESPACE
440
441#endif /* QSTRINGVIEW_H */
442