1// Copyright (C) 2021 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3#ifndef QBYTEARRAYVIEW_H
4#define QBYTEARRAYVIEW_H
5
6#include <QtCore/qbytearrayalgorithms.h>
7#include <QtCore/qcompare.h>
8#include <QtCore/qcontainerfwd.h>
9#include <QtCore/qstringfwd.h>
10#include <QtCore/qarraydata.h>
11
12#include <string>
13#include <string_view>
14#include <QtCore/q20type_traits.h>
15
16QT_BEGIN_NAMESPACE
17
18namespace QtPrivate {
19
20template <typename Byte>
21struct IsCompatibleByteTypeHelper : std::false_type {};
22template <> struct IsCompatibleByteTypeHelper<char> : std::true_type {};
23template <> struct IsCompatibleByteTypeHelper<signed char> : std::true_type {};
24template <> struct IsCompatibleByteTypeHelper<unsigned char> : std::true_type {};
25template <> struct IsCompatibleByteTypeHelper<std::byte> : std::true_type {};
26
27template <typename Byte>
28struct IsCompatibleByteType
29 : IsCompatibleByteTypeHelper<q20::remove_cvref_t<Byte>> {};
30
31template <typename Pointer>
32struct IsCompatibleByteArrayPointerHelper : std::false_type {};
33template <typename Byte>
34struct IsCompatibleByteArrayPointerHelper<Byte *>
35 : IsCompatibleByteType<Byte> {};
36template<typename Pointer>
37struct IsCompatibleByteArrayPointer
38 : IsCompatibleByteArrayPointerHelper<q20::remove_cvref_t<Pointer>> {};
39
40template <typename T, typename Enable = void>
41struct IsContainerCompatibleWithQByteArrayView : std::false_type {};
42
43template <typename T>
44struct IsContainerCompatibleWithQByteArrayView<T, std::enable_if_t<
45 std::conjunction_v<
46 // lacking concepts and ranges, we accept any T whose std::data yields a suitable
47 // pointer ...
48 IsCompatibleByteArrayPointer<decltype(std::data(std::declval<const T &>()))>,
49 // ... and that has a suitable size ...
50 std::is_convertible<decltype(std::size(std::declval<const T &>())), qsizetype>,
51 // ... and it's a range as it defines an iterator-like API
52 IsCompatibleByteType<typename std::iterator_traits<decltype(
53 std::begin(std::declval<const T &>()))>::value_type>,
54 std::is_convertible<decltype(std::begin(std::declval<const T &>())
55 != std::end(std::declval<const T &>())),
56 bool>,
57
58 // This needs to be treated specially due to the empty vs null distinction
59 std::negation<std::is_same<std::decay_t<T>, QByteArray>>,
60
61 // We handle array literals specially for source compat reasons
62 std::negation<std::is_array<T>>,
63
64 // Don't make an accidental copy constructor
65 std::negation<std::is_same<std::decay_t<T>, QByteArrayView>>>>> : std::true_type {};
66
67// Used by QLatin1StringView too
68template <typename Char>
69static constexpr qsizetype lengthHelperPointer(const Char *data) noexcept
70{
71 // std::char_traits can only be used with one of the regular char types
72 // (char, char16_t, wchar_t, but not uchar or QChar), so we roll the loop
73 // out by ourselves.
74 qsizetype i = 0;
75 if (!data)
76 return i;
77 while (data[i] != Char(0))
78 ++i;
79 return i;
80}
81
82} // namespace QtPrivate
83
84class Q_CORE_EXPORT QByteArrayView
85{
86public:
87 typedef char storage_type;
88 typedef const char value_type;
89 typedef qptrdiff difference_type;
90 typedef qsizetype size_type;
91 typedef value_type &reference;
92 typedef value_type &const_reference;
93 typedef value_type *pointer;
94 typedef value_type *const_pointer;
95
96 typedef pointer iterator;
97 typedef const_pointer const_iterator;
98 typedef std::reverse_iterator<iterator> reverse_iterator;
99 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
100
101private:
102 template <typename Byte>
103 using if_compatible_byte =
104 typename std::enable_if_t<QtPrivate::IsCompatibleByteType<Byte>::value, bool>;
105
106 template <typename Pointer>
107 using if_compatible_pointer =
108 typename std::enable_if_t<QtPrivate::IsCompatibleByteArrayPointer<Pointer>::value,
109 bool>;
110
111 template <typename T>
112 using if_compatible_qbytearray_like =
113 typename std::enable_if_t<std::is_same_v<T, QByteArray>, bool>;
114
115 template <typename T>
116 using if_compatible_container =
117 typename std::enable_if_t<QtPrivate::IsContainerCompatibleWithQByteArrayView<T>::value,
118 bool>;
119
120 template <typename Container>
121 static constexpr qsizetype lengthHelperContainer(const Container &c) noexcept
122 {
123 return qsizetype(std::size(c));
124 }
125
126 static constexpr qsizetype lengthHelperCharArray(const char *data, size_t size) noexcept
127 {
128 const auto it = std::char_traits<char>::find(s: data, n: size, a: '\0');
129 const auto end = it ? it : std::next(x: data, n: size);
130 return qsizetype(std::distance(first: data, last: end));
131 }
132
133 template <typename Byte>
134 static const storage_type *castHelper(const Byte *data) noexcept
135 { return reinterpret_cast<const storage_type*>(data); }
136 static constexpr const storage_type *castHelper(const storage_type *data) noexcept
137 { return data; }
138
139public:
140 constexpr QByteArrayView() noexcept
141 : m_size(0), m_data(nullptr) {}
142 constexpr QByteArrayView(std::nullptr_t) noexcept
143 : QByteArrayView() {}
144
145 template <typename Byte, if_compatible_byte<Byte> = true>
146 constexpr QByteArrayView(const Byte *data, qsizetype len)
147 : m_size((Q_ASSERT(len >= 0), Q_ASSERT(data || !len), len)),
148 m_data(castHelper(data)) {}
149
150 template <typename Byte, if_compatible_byte<Byte> = true>
151 constexpr QByteArrayView(const Byte *first, const Byte *last)
152 : QByteArrayView(first, last - first) {}
153
154#ifdef Q_QDOC
155 template <typename Byte>
156 constexpr QByteArrayView(const Byte *data) noexcept;
157#else
158 template <typename Pointer, if_compatible_pointer<Pointer> = true>
159 constexpr QByteArrayView(const Pointer &data) noexcept
160 : QByteArrayView(
161 data, data ? QtPrivate::lengthHelperPointer(data) : 0) {}
162#endif
163
164#ifdef Q_QDOC
165 QByteArrayView(const QByteArray &data) noexcept;
166#else
167 template <typename ByteArray, if_compatible_qbytearray_like<ByteArray> = true>
168 QByteArrayView(const ByteArray &ba) noexcept
169 : QByteArrayView{ba.begin(), ba.size()} {}
170#endif
171
172 template <typename Container, if_compatible_container<Container> = true>
173 constexpr QByteArrayView(const Container &c) noexcept
174 : QByteArrayView(std::data(c), lengthHelperContainer(c)) {}
175 template <size_t Size>
176 constexpr QByteArrayView(const char (&data)[Size]) noexcept
177 : QByteArrayView(data, lengthHelperCharArray(data, size: Size)) {}
178
179#ifdef Q_QDOC
180 template <typename Byte, size_t Size>
181#else
182 template <typename Byte, size_t Size, if_compatible_byte<Byte> = true>
183#endif
184 [[nodiscard]] constexpr static QByteArrayView fromArray(const Byte (&data)[Size]) noexcept
185 { return QByteArrayView(data, Size); }
186 [[nodiscard]] inline QByteArray toByteArray() const; // defined in qbytearray.h
187
188 [[nodiscard]] constexpr qsizetype size() const noexcept { return m_size; }
189 [[nodiscard]] constexpr const_pointer data() const noexcept { return m_data; }
190 [[nodiscard]] constexpr const_pointer constData() const noexcept { return data(); }
191
192 [[nodiscard]] constexpr char operator[](qsizetype n) const
193 { verify(pos: n, n: 1); return m_data[n]; }
194
195 //
196 // QByteArray API
197 //
198 [[nodiscard]] constexpr char at(qsizetype n) const { return (*this)[n]; }
199
200 [[nodiscard]] constexpr QByteArrayView first(qsizetype n) const
201 { verify(pos: 0, n); return sliced(pos: 0, n); }
202 [[nodiscard]] constexpr QByteArrayView last(qsizetype n) const
203 { verify(pos: 0, n); return sliced(pos: size() - n, n); }
204 [[nodiscard]] constexpr QByteArrayView sliced(qsizetype pos) const
205 { verify(pos, n: 0); return QByteArrayView(data() + pos, size() - pos); }
206 [[nodiscard]] constexpr QByteArrayView sliced(qsizetype pos, qsizetype n) const
207 { verify(pos, n); return QByteArrayView(data() + pos, n); }
208
209 constexpr QByteArrayView &slice(qsizetype pos)
210 { *this = sliced(pos); return *this; }
211 constexpr QByteArrayView &slice(qsizetype pos, qsizetype n)
212 { *this = sliced(pos, n); return *this; }
213
214 [[nodiscard]] constexpr QByteArrayView chopped(qsizetype len) const
215 { verify(pos: 0, n: len); return sliced(pos: 0, n: size() - len); }
216
217 [[nodiscard]] constexpr QByteArrayView left(qsizetype n) const
218 { if (n < 0 || n > size()) n = size(); return QByteArrayView(data(), n); }
219 [[nodiscard]] constexpr QByteArrayView right(qsizetype n) const
220 { if (n < 0 || n > size()) n = size(); if (n < 0) n = 0; return QByteArrayView(data() + size() - n, n); }
221 [[nodiscard]] constexpr QByteArrayView mid(qsizetype pos, qsizetype n = -1) const
222 {
223 using namespace QtPrivate;
224 auto result = QContainerImplHelper::mid(originalLength: size(), position: &pos, length: &n);
225 return result == QContainerImplHelper::Null ? QByteArrayView()
226 : QByteArrayView(m_data + pos, n);
227 }
228
229 constexpr void truncate(qsizetype n)
230 { verify(pos: 0, n); m_size = n; }
231 constexpr void chop(qsizetype n)
232 { verify(pos: 0, n); m_size -= n; }
233
234 // Defined in qbytearray.cpp:
235 [[nodiscard]] QByteArrayView trimmed() const noexcept
236 { return QtPrivate::trimmed(s: *this); }
237 [[nodiscard]] short toShort(bool *ok = nullptr, int base = 10) const
238 { return QtPrivate::toIntegral<short>(data: *this, ok, base); }
239 [[nodiscard]] ushort toUShort(bool *ok = nullptr, int base = 10) const
240 { return QtPrivate::toIntegral<ushort>(data: *this, ok, base); }
241 [[nodiscard]] int toInt(bool *ok = nullptr, int base = 10) const
242 { return QtPrivate::toIntegral<int>(data: *this, ok, base); }
243 [[nodiscard]] uint toUInt(bool *ok = nullptr, int base = 10) const
244 { return QtPrivate::toIntegral<uint>(data: *this, ok, base); }
245 [[nodiscard]] long toLong(bool *ok = nullptr, int base = 10) const
246 { return QtPrivate::toIntegral<long>(data: *this, ok, base); }
247 [[nodiscard]] ulong toULong(bool *ok = nullptr, int base = 10) const
248 { return QtPrivate::toIntegral<ulong>(data: *this, ok, base); }
249 [[nodiscard]] qlonglong toLongLong(bool *ok = nullptr, int base = 10) const
250 { return QtPrivate::toIntegral<qlonglong>(data: *this, ok, base); }
251 [[nodiscard]] qulonglong toULongLong(bool *ok = nullptr, int base = 10) const
252 { return QtPrivate::toIntegral<qulonglong>(data: *this, ok, base); }
253 [[nodiscard]] float toFloat(bool *ok = nullptr) const
254 {
255 const auto r = QtPrivate::toFloat(a: *this);
256 if (ok)
257 *ok = bool(r);
258 return r.value_or(u: 0.0f);
259 }
260 [[nodiscard]] double toDouble(bool *ok = nullptr) const
261 {
262 const auto r = QtPrivate::toDouble(a: *this);
263 if (ok)
264 *ok = bool(r);
265 return r.value_or(u: 0.0);
266 }
267
268 [[nodiscard]] bool startsWith(QByteArrayView other) const noexcept
269 { return QtPrivate::startsWith(haystack: *this, needle: other); }
270 [[nodiscard]] constexpr bool startsWith(char c) const noexcept
271 { return !empty() && front() == c; }
272
273 [[nodiscard]] bool endsWith(QByteArrayView other) const noexcept
274 { return QtPrivate::endsWith(haystack: *this, needle: other); }
275 [[nodiscard]] constexpr bool endsWith(char c) const noexcept
276 { return !empty() && back() == c; }
277
278 [[nodiscard]] qsizetype indexOf(QByteArrayView a, qsizetype from = 0) const noexcept
279 { return QtPrivate::findByteArray(haystack: *this, from, needle: a); }
280 [[nodiscard]] qsizetype indexOf(char ch, qsizetype from = 0) const noexcept
281 { return QtPrivate::findByteArray(haystack: *this, from, needle: ch); }
282
283 [[nodiscard]] bool contains(QByteArrayView a) const noexcept
284 { return indexOf(a) != qsizetype(-1); }
285 [[nodiscard]] bool contains(char c) const noexcept
286 { return indexOf(ch: c) != qsizetype(-1); }
287
288 [[nodiscard]] qsizetype lastIndexOf(QByteArrayView a) const noexcept
289 { return lastIndexOf(a, from: size()); }
290 [[nodiscard]] qsizetype lastIndexOf(QByteArrayView a, qsizetype from) const noexcept
291 { return QtPrivate::lastIndexOf(haystack: *this, from, needle: a); }
292 [[nodiscard]] qsizetype lastIndexOf(char ch, qsizetype from = -1) const noexcept
293 { return QtPrivate::lastIndexOf(haystack: *this, from, needle: ch); }
294
295 [[nodiscard]] qsizetype count(QByteArrayView a) const noexcept
296 { return QtPrivate::count(haystack: *this, needle: a); }
297 [[nodiscard]] qsizetype count(char ch) const noexcept
298 { return QtPrivate::count(haystack: *this, needle: QByteArrayView(&ch, 1)); }
299
300 inline int compare(QByteArrayView a, Qt::CaseSensitivity cs = Qt::CaseSensitive) const noexcept;
301
302 [[nodiscard]] inline bool isValidUtf8() const noexcept { return QtPrivate::isValidUtf8(s: *this); }
303
304 //
305 // STL compatibility API:
306 //
307 [[nodiscard]] constexpr const_iterator begin() const noexcept { return data(); }
308 [[nodiscard]] constexpr const_iterator end() const noexcept { return data() + size(); }
309 [[nodiscard]] constexpr const_iterator cbegin() const noexcept { return begin(); }
310 [[nodiscard]] constexpr const_iterator cend() const noexcept { return end(); }
311 [[nodiscard]] constexpr const_reverse_iterator rbegin() const noexcept { return const_reverse_iterator(end()); }
312 [[nodiscard]] constexpr const_reverse_iterator rend() const noexcept { return const_reverse_iterator(begin()); }
313 [[nodiscard]] constexpr const_reverse_iterator crbegin() const noexcept { return rbegin(); }
314 [[nodiscard]] constexpr const_reverse_iterator crend() const noexcept { return rend(); }
315
316 [[nodiscard]] constexpr bool empty() const noexcept { return size() == 0; }
317 [[nodiscard]] constexpr char front() const { Q_ASSERT(!empty()); return m_data[0]; }
318 [[nodiscard]] constexpr char back() const { Q_ASSERT(!empty()); return m_data[m_size - 1]; }
319
320 [[nodiscard]] constexpr Q_IMPLICIT operator std::string_view() const noexcept
321 { return std::string_view(m_data, size_t(m_size)); }
322
323 [[nodiscard]] constexpr qsizetype max_size() const noexcept { return maxSize(); }
324
325 //
326 // Qt compatibility API:
327 //
328 [[nodiscard]] constexpr bool isNull() const noexcept { return !m_data; }
329 [[nodiscard]] constexpr bool isEmpty() const noexcept { return empty(); }
330 [[nodiscard]] constexpr qsizetype length() const noexcept
331 { return size(); }
332 [[nodiscard]] constexpr char first() const { return front(); }
333 [[nodiscard]] constexpr char last() const { return back(); }
334
335 [[nodiscard]] static constexpr qsizetype maxSize() noexcept
336 {
337 // -1 to deal with the pointer one-past-the-end;
338 return QtPrivate::MaxAllocSize - 1;
339 }
340
341private:
342 Q_ALWAYS_INLINE constexpr void verify([[maybe_unused]] qsizetype pos = 0,
343 [[maybe_unused]] qsizetype n = 1) const
344 {
345 Q_ASSERT(pos >= 0);
346 Q_ASSERT(pos <= size());
347 Q_ASSERT(n >= 0);
348 Q_ASSERT(n <= size() - pos);
349 }
350
351 friend bool
352 comparesEqual(const QByteArrayView &lhs, const QByteArrayView &rhs) noexcept
353 {
354 return lhs.size() == rhs.size()
355 && (!lhs.size() || memcmp(s1: lhs.data(), s2: rhs.data(), n: lhs.size()) == 0);
356 }
357 friend Qt::strong_ordering
358 compareThreeWay(const QByteArrayView &lhs, const QByteArrayView &rhs) noexcept
359 {
360 const int res = QtPrivate::compareMemory(lhs, rhs);
361 return Qt::compareThreeWay(lhs: res, rhs: 0);
362 }
363 Q_DECLARE_STRONGLY_ORDERED(QByteArrayView)
364
365 friend bool comparesEqual(const QByteArrayView &lhs, const char *rhs) noexcept
366 { return comparesEqual(lhs, rhs: QByteArrayView(rhs)); }
367 friend Qt::strong_ordering
368 compareThreeWay(const QByteArrayView &lhs, const char *rhs) noexcept
369 { return compareThreeWay(lhs, rhs: QByteArrayView(rhs)); }
370 Q_DECLARE_STRONGLY_ORDERED(QByteArrayView, const char *)
371
372 // defined in qstring.cpp
373 friend Q_CORE_EXPORT bool
374 comparesEqual(const QByteArrayView &lhs, const QChar &rhs) noexcept;
375 friend Q_CORE_EXPORT Qt::strong_ordering
376 compareThreeWay(const QByteArrayView &lhs, const QChar &rhs) noexcept;
377 friend Q_CORE_EXPORT bool
378 comparesEqual(const QByteArrayView &lhs, char16_t rhs) noexcept;
379 friend Q_CORE_EXPORT Qt::strong_ordering
380 compareThreeWay(const QByteArrayView &lhs, char16_t rhs) noexcept;
381#if !defined(QT_NO_CAST_FROM_ASCII) && !defined(QT_RESTRICTED_CAST_FROM_ASCII)
382 Q_DECLARE_STRONGLY_ORDERED(QByteArrayView, QChar, QT_ASCII_CAST_WARN)
383 Q_DECLARE_STRONGLY_ORDERED(QByteArrayView, char16_t, QT_ASCII_CAST_WARN)
384#endif // !defined(QT_NO_CAST_FROM_ASCII) && !defined(QT_RESTRICTED_CAST_FROM_ASCII)
385
386 qsizetype m_size;
387 const storage_type *m_data;
388};
389Q_DECLARE_TYPEINFO(QByteArrayView, Q_PRIMITIVE_TYPE);
390
391template<typename QByteArrayLike,
392 std::enable_if_t<std::is_same_v<QByteArrayLike, QByteArray>, bool> = true>
393[[nodiscard]] inline QByteArrayView qToByteArrayViewIgnoringNull(const QByteArrayLike &b) noexcept
394{ return QByteArrayView(b.begin(), b.size()); }
395
396inline int QByteArrayView::compare(QByteArrayView a, Qt::CaseSensitivity cs) const noexcept
397{
398 return cs == Qt::CaseSensitive ? QtPrivate::compareMemory(lhs: *this, rhs: a) :
399 qstrnicmp(data(), size(), a.data(), a.size());
400}
401
402#if QT_DEPRECATED_SINCE(6, 0)
403QT_DEPRECATED_VERSION_X_6_0("Use the QByteArrayView overload.")
404inline quint16 qChecksum(const char *s, qsizetype len,
405 Qt::ChecksumType standard = Qt::ChecksumIso3309)
406{ return qChecksum(data: QByteArrayView(s, len), standard); }
407#endif
408
409qsizetype QtPrivate::findByteArray(QByteArrayView haystack, qsizetype from, char needle) noexcept
410{
411 if (from < 0)
412 from = qMax(a: from + haystack.size(), b: qsizetype(0));
413 if (from < haystack.size()) {
414 const char *const b = haystack.data();
415 if (const auto n = static_cast<const char *>(
416 memchr(s: b + from, c: needle, n: static_cast<size_t>(haystack.size() - from)))) {
417 return n - b;
418 }
419 }
420 return -1;
421}
422
423qsizetype QtPrivate::lastIndexOf(QByteArrayView haystack, qsizetype from, uchar needle) noexcept
424{
425 if (from < 0)
426 from = qMax(a: from + haystack.size(), b: qsizetype(0));
427 else
428 from = qMin(a: from, b: haystack.size() - 1);
429
430 const char *const b = haystack.data();
431 const void *n = b ? qmemrchr(s: b, needle, n: from + 1) : nullptr;
432 return n ? static_cast<const char *>(n) - b : -1;
433}
434
435QT_END_NAMESPACE
436
437#endif // QBYTEARRAYVIEW_H
438

source code of qtbase/src/corelib/text/qbytearrayview.h