Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qanystringview.h
Go to the documentation of this file.
1// Copyright (C) 2022 The Qt Company Ltd.
2// Copyright (C) 2020 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Marc Mutz <marc.mutz@kdab.com>
3// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
4#ifndef QANYSTRINGVIEW_H
5#define QANYSTRINGVIEW_H
6
7#include <QtCore/qcompare.h>
8#include <QtCore/qcontainerfwd.h>
9#include <QtCore/qlatin1stringview.h>
10#include <QtCore/qstringview.h>
11#include <QtCore/qutf8stringview.h>
12
13#include <QtCore/q20type_traits.h>
14#include <limits>
15
16class tst_QAnyStringView;
17
18QT_BEGIN_NAMESPACE
19
20namespace QtPrivate {
21
22template <typename Tag, typename Result>
23struct wrapped { using type = Result; };
24
25template <typename Tag, typename Result>
26using wrapped_t = typename wrapped<Tag, Result>::type;
27
28} // namespace QtPrivate
29
31{
32public:
35private:
36 static constexpr size_t SizeMask = (std::numeric_limits<size_t>::max)() / 4;
37#if QT_VERSION >= QT_VERSION_CHECK(7, 0, 0) || defined(QT_BOOTSTRAPPED)
38 static constexpr int SizeShift = 2;
39 static constexpr size_t Latin1Flag = 1;
40#else
41 static constexpr int SizeShift = 0;
42 static constexpr size_t Latin1Flag = SizeMask + 1;
43#endif
44 static constexpr size_t TwoByteCodePointFlag = Latin1Flag << 1;
45 static constexpr size_t TypeMask = ~(SizeMask << SizeShift);
46 static_assert(TypeMask == (Latin1Flag|TwoByteCodePointFlag));
47
48 // Tag bits
49 // 0 0 Utf8
50 // 0 1 Latin1
51 // 1 0 Utf16
52 // 1 1 Unused
53 // ^ ^ latin1
54 // | sizeof code-point == 2
55 enum Tag : size_t {
56 Utf8 = 0,
57 Latin1 = Latin1Flag,
58 Utf16 = TwoByteCodePointFlag,
59 Unused = TypeMask,
60 };
61
62 template <typename Char>
66 >;
67
68 template <typename Char>
70
71 template <typename Pointer>
75 >, bool>;
76
77
78 template <typename T>
82 >, bool>;
83
84 template <typename QStringOrQByteArray, typename T>
86 // need to exclude a bunch of stuff, because we take by universal reference:
89 std::is_same<q20::remove_cvref_t<T>, QAnyStringView>, // don't make a copy/move ctor
90 std::is_pointer<std::decay_t<T>>, // const char*, etc
91 is_compatible_char<T>, // don't create a QString/QByteArray, we have a ctor
94 >>,
95 // this is what we're really after:
97 >, bool>;
98
99 // confirm we don't make an accidental copy constructor:
102
103 template<typename Char>
104 static constexpr bool isAsciiOnlyCharsAtCompileTime(Char *str, qsizetype sz) noexcept
105 {
106 // do not perform check if not at compile time
107 if (!q20::is_constant_evaluated())
108 return false;
109 if constexpr (sizeof(Char) != sizeof(char)) {
110 Q_UNUSED(str);
111 Q_UNUSED(sz);
112 return false;
113 } else {
114 for (qsizetype i = 0; i < sz; ++i) {
115 if (uchar(str[i]) > 0x7f)
116 return false;
117 }
118 return true;
119 }
120 }
121
122 template<typename Char>
123 static constexpr std::size_t encodeType(const Char *str, qsizetype sz) noexcept
124 {
125 // Utf16 if 16 bit, Latin1 if ASCII, else Utf8
126 Q_ASSERT(sz >= 0);
127 Q_ASSERT(sz <= qsizetype(SizeMask));
128 Q_ASSERT(str || !sz);
129 return (std::size_t(sz) << SizeShift)
130 | uint(sizeof(Char) == sizeof(char16_t)) * Tag::Utf16
131 | uint(isAsciiOnlyCharsAtCompileTime(str, sz)) * Tag::Latin1;
132 }
133
134 template <typename Char>
135 static constexpr qsizetype lengthHelperPointer(const Char *str) noexcept
136 {
137 if (q20::is_constant_evaluated())
138 return QtPrivate::lengthHelperPointer(str);
139 if constexpr (sizeof(Char) == sizeof(char16_t))
140 return QtPrivate::qustrlen(reinterpret_cast<const char16_t*>(str));
141 else
142 return qsizetype(strlen(reinterpret_cast<const char*>(str)));
143 }
144
145 static QChar toQChar(char ch) noexcept { return toQChar(QLatin1Char{ch}); } // we don't handle UTF-8 multibytes
146 static QChar toQChar(QChar ch) noexcept { return ch; }
147 static QChar toQChar(QLatin1Char ch) noexcept { return ch; }
148
149 struct QCharContainer { // private, so users can't pass their own
150 explicit QCharContainer() = default;
151 QChar ch;
152 };
153
154 template <typename Char>
155 static constexpr QAnyStringView fromCharInternal(const Char &ch) noexcept
156 {
157 if constexpr (sizeof ch == 1) // even char8_t is Latin-1 as single octet
158 return QAnyStringView{&ch, 1, size_t{Tag::Latin1}};
159 else // sizeof ch == 2
160 return {&ch, 1};
161 }
162
163 explicit constexpr QAnyStringView(const void *d, qsizetype n, std::size_t sizeAndType) noexcept
164 : m_data{d}, m_size{std::size_t(n) | (sizeAndType & TypeMask)} {}
165public:
166 constexpr QAnyStringView() noexcept
167 : m_data{nullptr}, m_size{0} {}
168 constexpr QAnyStringView(std::nullptr_t) noexcept
170
171 template <typename Char, if_compatible_char<Char> = true>
172 constexpr QAnyStringView(const Char *str, qsizetype len)
173 : m_data{str}, m_size{encodeType<Char>(str, len)}
174 {
175 }
176
177 template <typename Char, if_compatible_char<Char> = true>
178 constexpr QAnyStringView(const Char *f, const Char *l)
179 : QAnyStringView(f, l - f) {}
180
181#ifdef Q_QDOC
182 template <typename Char, size_t N>
183 constexpr QAnyStringView(const Char (&array)[N]) noexcept;
184
185 template <typename Char>
186 constexpr QAnyStringView(const Char *str) noexcept;
187#else
188
189 template <typename Pointer, if_compatible_pointer<Pointer> = true>
190 constexpr QAnyStringView(const Pointer &str) noexcept
191 : QAnyStringView{str, str ? lengthHelperPointer(str) : 0} {}
192#endif
193
194 // defined in qstring.h
195 inline QAnyStringView(const QByteArray &str) noexcept; // TODO: Should we have this at all? Remove?
196 inline QAnyStringView(const QString &str) noexcept;
197 inline constexpr QAnyStringView(QLatin1StringView str) noexcept;
198
199 template <typename Container, if_compatible_container<Container> = true>
202
203 template <typename Container, if_convertible_to<QString, Container> = true>
204 constexpr QAnyStringView(Container &&c, QtPrivate::wrapped_t<Container, QString> &&capacity = {})
205 //noexcept(std::is_nothrow_constructible_v<QString, Container>)
207
208 template <typename Container, if_convertible_to<QByteArray, Container> = true>
209 constexpr QAnyStringView(Container &&c, QtPrivate::wrapped_t<Container, QByteArray> &&capacity = {})
210 //noexcept(std::is_nothrow_constructible_v<QByteArray, Container>)
212
213 template <typename Char, if_compatible_char<Char> = true>
214 constexpr QAnyStringView(const Char &c) noexcept
215 : QAnyStringView{fromCharInternal(c)} {}
216 template <typename Char, if_convertible_to<QChar, Char> = true>
217 constexpr QAnyStringView(Char ch, QCharContainer &&capacity = QCharContainer()) noexcept
218 : QAnyStringView{&(capacity.ch = ch), 1} {}
219 template <typename Char, typename Container = decltype(QChar::fromUcs4(U'x')),
220 std::enable_if_t<std::is_same_v<Char, char32_t>, bool> = true>
221 constexpr QAnyStringView(Char c, Container &&capacity = {}) noexcept
223
226
227 template <bool UseChar8T>
230
231 template <typename Char, size_t Size, if_compatible_char<Char> = true>
232 [[nodiscard]] constexpr static QAnyStringView fromArray(const Char (&string)[Size]) noexcept
233 { return QAnyStringView(string, Size); }
234
235 // defined in qstring.h:
236 template <typename Visitor>
237 inline constexpr decltype(auto) visit(Visitor &&v) const;
238
239 [[nodiscard]]
240 constexpr QAnyStringView mid(qsizetype pos, qsizetype n = -1) const
241 {
242 using namespace QtPrivate;
243 auto result = QContainerImplHelper::mid(size(), &pos, &n);
244 return result == QContainerImplHelper::Null ? QAnyStringView() : sliced(pos, n);
245 }
246 [[nodiscard]]
247 constexpr QAnyStringView left(qsizetype n) const
248 {
249 if (size_t(n) >= size_t(size()))
250 n = size();
251 return sliced(0, n);
252 }
253 [[nodiscard]]
254 constexpr QAnyStringView right(qsizetype n) const
255 {
256 if (size_t(n) >= size_t(size()))
257 n = size();
258 return sliced(size() - n, n);
259 }
260
261 [[nodiscard]] constexpr QAnyStringView sliced(qsizetype pos) const
262 { verify(pos, 0); auto r = *this; r.advanceData(pos); r.setSize(size() - pos); return r; }
263 [[nodiscard]] constexpr QAnyStringView sliced(qsizetype pos, qsizetype n) const
264 { verify(pos, n); auto r = *this; r.advanceData(pos); r.setSize(n); return r; }
265 [[nodiscard]] constexpr QAnyStringView first(qsizetype n) const
266 { verify(0, n); return sliced(0, n); }
267 [[nodiscard]] constexpr QAnyStringView last(qsizetype n) const
268 { verify(0, n); return sliced(size() - n, n); }
269 [[nodiscard]] constexpr QAnyStringView chopped(qsizetype n) const
270 { verify(0, n); return sliced(0, size() - n); }
271
272 constexpr QAnyStringView &slice(qsizetype pos)
273 { *this = sliced(pos); return *this; }
274 constexpr QAnyStringView &slice(qsizetype pos, qsizetype n)
275 { *this = sliced(pos, n); return *this; }
276
277 constexpr void truncate(qsizetype n)
278 { verify(0, n); setSize(n); }
279 constexpr void chop(qsizetype n)
280 { verify(0, n); setSize(size() - n); }
281
282 template <typename...Args>
283 [[nodiscard]] inline QString arg(Args &&...args) const;
284
285 [[nodiscard]] inline QString toString() const; // defined in qstring.h
286
287 [[nodiscard]] constexpr qsizetype size() const noexcept
288 { return qsizetype((m_size >> SizeShift) & SizeMask); }
289 [[nodiscard]] constexpr const void *data() const noexcept { return m_data; }
290
291 [[nodiscard]] Q_CORE_EXPORT static int compare(QAnyStringView lhs, QAnyStringView rhs, Qt::CaseSensitivity cs = Qt::CaseSensitive) noexcept;
292 [[nodiscard]] Q_CORE_EXPORT static bool equal(QAnyStringView lhs, QAnyStringView rhs) noexcept;
293
294 static constexpr inline bool detects_US_ASCII_at_compile_time =
295#ifdef QT_SUPPORTS_IS_CONSTANT_EVALUATED
296 true
297#else
298 false
299#endif
300 ;
301
302 //
303 // STL compatibility API:
304 //
305 [[nodiscard]] constexpr QChar front() const; // NOT noexcept!
306 [[nodiscard]] constexpr QChar back() const; // NOT noexcept!
307 [[nodiscard]] constexpr bool empty() const noexcept { return size() == 0; }
308 [[nodiscard]] constexpr qsizetype size_bytes() const noexcept
309 { return size() * charSize(); }
310
311 [[nodiscard]] constexpr qsizetype max_size() const noexcept
312 {
313 // -1 to deal with the pointer one-past-the-end;
314 return QtPrivate::MaxAllocSize / charSize() - 1;
315 }
316
317 //
318 // Qt compatibility API:
319 //
320 [[nodiscard]] constexpr bool isNull() const noexcept { return !m_data; }
321 [[nodiscard]] constexpr bool isEmpty() const noexcept { return empty(); }
322 [[nodiscard]] constexpr qsizetype length() const noexcept
323 { return size(); }
324
325private:
326 friend bool comparesEqual(const QAnyStringView &lhs, const QAnyStringView &rhs) noexcept
327 { return QAnyStringView::equal(lhs, rhs); }
328 friend Qt::strong_ordering
329 compareThreeWay(const QAnyStringView &lhs, const QAnyStringView &rhs) noexcept
330 {
331 const int res = QAnyStringView::compare(lhs, rhs);
332 return Qt::compareThreeWay(res, 0);
333 }
335
336#ifndef QT_NO_DEBUG_STREAM
338#endif
339
340 [[nodiscard]] constexpr Tag tag() const noexcept { return Tag{m_size & TypeMask}; }
341 [[nodiscard]] constexpr bool isUtf16() const noexcept { return tag() == Tag::Utf16; }
342 [[nodiscard]] constexpr bool isUtf8() const noexcept { return tag() == Tag::Utf8; }
343 [[nodiscard]] constexpr bool isLatin1() const noexcept { return tag() == Tag::Latin1; }
344 [[nodiscard]] constexpr QStringView asStringView() const
345 { return Q_ASSERT(isUtf16()), QStringView{m_data_utf16, size()}; }
346 [[nodiscard]] constexpr q_no_char8_t::QUtf8StringView asUtf8StringView() const
347 { return Q_ASSERT(isUtf8()), q_no_char8_t::QUtf8StringView{m_data_utf8, size()}; }
348 [[nodiscard]] inline constexpr QLatin1StringView asLatin1StringView() const;
349 [[nodiscard]] constexpr size_t charSize() const noexcept { return isUtf16() ? 2 : 1; }
350 constexpr void setSize(qsizetype sz) noexcept { m_size = size_t(sz) | tag(); }
351 constexpr void advanceData(qsizetype delta) noexcept
352 { m_data_utf8 += delta * charSize(); }
353 Q_ALWAYS_INLINE constexpr void verify([[maybe_unused]] qsizetype pos = 0,
354 [[maybe_unused]] qsizetype n = 1) const
355 {
356 Q_ASSERT(pos >= 0);
357 Q_ASSERT(pos <= size());
358 Q_ASSERT(n >= 0);
359 Q_ASSERT(n <= size() - pos);
360 }
361 union {
362 const void *m_data;
363 const char *m_data_utf8;
364 const char16_t *m_data_utf16;
365 };
366 size_t m_size;
367 friend class ::tst_QAnyStringView;
368};
370
371template <typename QStringLike, std::enable_if_t<std::disjunction_v<
372 std::is_same<QStringLike, QString>,
373 std::is_same<QStringLike, QByteArray>
374 >, bool> = true>
375[[nodiscard]] inline QAnyStringView qToAnyStringViewIgnoringNull(const QStringLike &s) noexcept
376{ return QAnyStringView(s.begin(), s.size()); }
377
378QT_END_NAMESPACE
379
380#endif /* QANYSTRINGVIEW_H */
\inmodule QtCore
constexpr QChar back() const
Returns the last character in the string view.
Definition qstring.h:122
constexpr const void * data() const noexcept
Returns a const pointer to the first character in the string view.
constexpr QAnyStringView sliced(qsizetype pos, qsizetype n) const
static constexpr bool detects_US_ASCII_at_compile_time
constexpr QAnyStringView left(qsizetype n) const
qsizetype size_type
Alias for qsizetype.
constexpr QAnyStringView(Char ch, QCharContainer &&capacity=QCharContainer()) noexcept
constexpr QAnyStringView & slice(qsizetype pos)
constexpr QAnyStringView last(qsizetype n) const
const char * m_data_utf8
constexpr qsizetype size() const noexcept
Returns the size of this string view, in the encoding's code points.
constexpr QAnyStringView & slice(qsizetype pos, qsizetype n)
constexpr QAnyStringView(const Char *str, qsizetype len)
Constructs a string view on str with length len.
QString toString() const
Returns a deep copy of this string view's data as a QString.
Definition qstring.h:1227
constexpr QAnyStringView first(qsizetype n) const
constexpr QAnyStringView right(qsizetype n) const
static Q_CORE_EXPORT int compare(QAnyStringView lhs, QAnyStringView rhs, Qt::CaseSensitivity cs=Qt::CaseSensitive) noexcept
Compares the string view lhs with the string view rhs and returns a negative integer if lhs is less t...
Definition qstring.cpp:1593
constexpr bool isEmpty() const noexcept
Returns whether this string view is empty - that is, whether {size() == 0}.
static Q_CORE_EXPORT bool equal(QAnyStringView lhs, QAnyStringView rhs) noexcept
Definition qstring.cpp:1440
friend bool comparesEqual(const QAnyStringView &lhs, const QAnyStringView &rhs) noexcept
const void * m_data
constexpr qsizetype size_bytes() const noexcept
Returns the size of this string view, but in bytes, not code-points.
constexpr QAnyStringView sliced(qsizetype pos) const
constexpr QAnyStringView mid(qsizetype pos, qsizetype n=-1) const
constexpr QAnyStringView(Container &&c, QtPrivate::wrapped_t< Container, QString > &&capacity={})
constexpr QAnyStringView chopped(qsizetype n) const
constexpr bool isNull() const noexcept
Returns whether this string view is null - that is, whether {data() == nullptr}.
constexpr QAnyStringView() noexcept
Constructs a null string view.
const char16_t * m_data_utf16
constexpr QAnyStringView(const Char *f, const Char *l)
Constructs a string view on first with length (last - first).
constexpr QChar front() const
Returns the first character in the string view.
Definition qstring.h:118
QString arg(Args &&...args) const
Definition qstring.h:1632
constexpr QAnyStringView(std::nullptr_t) noexcept
Constructs a null string view.
constexpr void chop(qsizetype n)
qptrdiff difference_type
Alias for {std::ptrdiff_t}.
constexpr void truncate(qsizetype n)
constexpr QAnyStringView(QLatin1StringView str) noexcept
Definition qstring.h:93
constexpr bool empty() const noexcept
Returns whether this string view is empty - that is, whether {size() == 0}.
constexpr QAnyStringView(const Pointer &str) noexcept
constexpr qsizetype length() const noexcept
Same as size().
constexpr qsizetype max_size() const noexcept
friend Qt::strong_ordering compareThreeWay(const QAnyStringView &lhs, const QAnyStringView &rhs) noexcept
QAnyStringView(const QByteArray &str) noexcept
Constructs a string view on str.
Definition qstring.h:1222
Combined button and popup list for selecting options.
\macro QT_NO_KEYWORDS >
Definition qcompare.h:24
Q_DECLARE_TYPEINFO(QAnyStringView, Q_PRIMITIVE_TYPE)