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
qcontainertools_impl.h
Go to the documentation of this file.
1// Copyright (C) 2018 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Marc Mutz <marc.mutz@kdab.com>
2// Copyright (C) 2018 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Giuseppe D'Angelo <giuseppe.dangelo@kdab.com>
3// Copyright (C) 2020 The Qt Company Ltd.
4// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
5// Qt-Security score:significant reason:default
6
7#if 0
8#pragma qt_sync_skip_header_check
9#pragma qt_sync_stop_processing
10#endif
11
12#ifndef QCONTAINERTOOLS_IMPL_H
13#define QCONTAINERTOOLS_IMPL_H
14
15#include <QtCore/qglobal.h>
16#include <QtCore/qnamespace.h>
17#include <QtCore/qtypeinfo.h>
18
19#include <QtCore/q20type_traits.h>
20#include <QtCore/qxptype_traits.h>
21
22#include <cstring>
23#include <iterator>
24#include <memory>
25#include <algorithm>
26
27QT_BEGIN_NAMESPACE
28
29namespace QtPrivate
30{
31
32/*!
33 \internal
34
35 Returns whether \a p is within a range [b, e). In simplest form equivalent to:
36 b <= p < e.
37*/
38template <typename T>
39inline constexpr bool q_points_into_range(const T *p, const T *b, const T *e)
40{
41 if (q20::is_constant_evaluated()) {
42 for (; b != e; ++b) {
43 if (b == p)
44 return true;
45 }
46 return false;
47 }
48 return !std::less{}(p, b) && std::less{}(p, e);
49}
50
51/*!
52 \internal
53
54 Returns whether \a p is within container \a c. In its simplest form equivalent to:
55 c.data() <= p < c.data() + c.size()
56*/
57template <typename C, typename T>
58inline constexpr bool q_points_into_range(const T &p, const C &c) noexcept
59{
60 static_assert(std::is_same_v<decltype(std::data(c)), T>);
61
62 // std::distance because QArrayDataPointer has a "qsizetype size"
63 // member but no size() function
64 return q_points_into_range(p, std::data(c),
65 std::data(c) + std::distance(std::begin(c), std::end(c)));
66}
67
68QT_WARNING_PUSH
69QT_WARNING_DISABLE_GCC("-Wmaybe-uninitialized")
70
71template <typename T, typename N>
79
80template <typename T, typename N>
81void q_uninitialized_relocate_n(T* first, N n, T* out)
82{
83 if constexpr (QTypeInfo<T>::isRelocatable) {
84 static_assert(std::is_copy_constructible_v<T> || std::is_move_constructible_v<T>,
85 "Refusing to relocate this non-copy/non-move-constructible type.");
86 // Even if n == 0, out == nullptr or first == nullptr are UB for memcpy().
87 // Negative n shouldn't happen, but the compiler can't see that and might warn about
88 // memcpy being called with an out-of-range argument. Since we need to check for n == 0
89 // anyway, check for n > 0 instead and assert below.
90 if (n > N(0)) {
91 std::memcpy(static_cast<void *>(out),
92 static_cast<const void *>(first),
93 n * sizeof(T));
94 } else {
95 Q_ASSERT(n == N(0));
96 }
97 } else {
98 q_uninitialized_move_if_noexcept_n(first, n, out);
99 if constexpr (QTypeInfo<T>::isComplex)
100 std::destroy_n(first, n);
101 }
102}
103
105
106/*!
107 \internal
108
109 A wrapper around std::rotate(), with an optimization for
110 Q_RELOCATABLE_TYPEs. We omit the return value, as it would be more work to
111 compute in the Q_RELOCATABLE_TYPE case and, unlike std::rotate on
112 ForwardIterators, callers can compute the result in constant time
113 themselves.
114*/
115template <typename T>
117{
118 if constexpr (QTypeInfo<T>::isRelocatable) {
119 const auto cast = [](T *p) { return reinterpret_cast<uchar*>(p); };
121 } else {
122 std::rotate(first, mid, last);
123 }
124}
125
126/*!
127 \internal
128 Copies all elements, except the ones for which \a pred returns \c true, from
129 range [first, last), to the uninitialized memory buffer starting at \a out.
130
131 It's undefined behavior if \a out points into [first, last).
132
133 Returns a pointer one past the last copied element.
134
135 If an exception is thrown, all the already copied elements in the destination
136 buffer are destroyed.
137*/
138template <typename T, typename Predicate>
139T *q_uninitialized_remove_copy_if(T *first, T *last, T *out, Predicate &pred)
140{
141 static_assert(std::is_nothrow_destructible_v<T>,
142 "This algorithm requires that T has a non-throwing destructor");
143 Q_ASSERT(!q_points_into_range(out, first, last));
144
145 T *dest_begin = out;
146 QT_TRY {
147 while (first != last) {
148 if (!pred(*first)) {
149 new (std::addressof(*out)) T(*first);
150 ++out;
151 }
152 ++first;
153 }
154 } QT_CATCH (...) {
155 std::destroy(std::reverse_iterator(out), std::reverse_iterator(dest_begin));
156 QT_RETHROW;
157 }
158 return out;
159}
160
161template<typename iterator, typename N>
162void q_relocate_overlap_n_left_move(iterator first, N n, iterator d_first)
163{
164 // requires: [first, n) is a valid range
165 // requires: d_first + n is reachable from d_first
166 // requires: iterator is at least a random access iterator
167 // requires: value_type(iterator) has a non-throwing destructor
168
169 Q_ASSERT(n);
170 Q_ASSERT(d_first < first); // only allow moves to the "left"
171 using T = typename std::iterator_traits<iterator>::value_type;
172
173 // Watches passed iterator. Unless commit() is called, all the elements that
174 // the watched iterator passes through are deleted at the end of object
175 // lifetime. freeze() could be used to stop watching the passed iterator and
176 // remain at current place.
177 //
178 // requires: the iterator is expected to always point to an invalid object
179 // (to uninitialized memory)
180 struct Destructor
181 {
182 iterator *iter;
183 iterator end;
184 iterator intermediate;
185
186 Destructor(iterator &it) noexcept : iter(std::addressof(it)), end(it) { }
187 void commit() noexcept { iter = std::addressof(end); }
188 void freeze() noexcept
189 {
190 intermediate = *iter;
191 iter = std::addressof(intermediate);
192 }
193 ~Destructor() noexcept
194 {
195 for (const int step = *iter < end ? 1 : -1; *iter != end;) {
196 std::advance(*iter, step);
197 (*iter)->~T();
198 }
199 }
200 } destroyer(d_first);
201
202 const iterator d_last = d_first + n;
203 // Note: use pair and explicitly copy iterators from it to prevent
204 // accidental reference semantics instead of copy. equivalent to:
205 //
206 // auto [overlapBegin, overlapEnd] = std::minmax(d_last, first);
207 auto pair = std::minmax(d_last, first);
208
209 // overlap area between [d_first, d_first + n) and [first, first + n) or an
210 // uninitialized memory area between the two ranges
211 iterator overlapBegin = pair.first;
212 iterator overlapEnd = pair.second;
213
214 // move construct elements in uninitialized region
215 while (d_first != overlapBegin) {
216 // account for std::reverse_iterator, cannot use new(d_first) directly
217 new (std::addressof(*d_first)) T(std::move_if_noexcept(*first));
218 ++d_first;
219 ++first;
220 }
221
222 // cannot commit but have to stop - there might be an overlap region
223 // which we don't want to delete (because it's part of existing data)
224 destroyer.freeze();
225
226 // move assign elements in overlap region
227 while (d_first != d_last) {
228 *d_first = std::move_if_noexcept(*first);
229 ++d_first;
230 ++first;
231 }
232
233 Q_ASSERT(d_first == destroyer.end + n);
234 destroyer.commit(); // can commit here as ~T() below does not throw
235
236 while (first != overlapEnd)
237 (--first)->~T();
238}
239
240/*!
241 \internal
242
243 Relocates a range [first, n) to [d_first, n) taking care of potential memory
244 overlaps. This is a generic equivalent of memmove.
245
246 If an exception is thrown during the relocation, all the relocated elements
247 are destroyed and [first, n) may contain valid but unspecified values,
248 including moved-from values (basic exception safety).
249*/
250template<typename T, typename N>
251void q_relocate_overlap_n(T *first, N n, T *d_first)
252{
253 static_assert(std::is_nothrow_destructible_v<T>,
254 "This algorithm requires that T has a non-throwing destructor");
255
256 if (n == N(0) || first == d_first || first == nullptr || d_first == nullptr)
257 return;
258
259 if constexpr (QTypeInfo<T>::isRelocatable) {
260 std::memmove(static_cast<void *>(d_first), static_cast<const void *>(first), n * sizeof(T));
261 } else { // generic version has to be used
262 if (d_first < first) {
263 q_relocate_overlap_n_left_move(first, n, d_first);
264 } else { // first < d_first
265 auto rfirst = std::make_reverse_iterator(first + n);
266 auto rd_first = std::make_reverse_iterator(d_first + n);
267 q_relocate_overlap_n_left_move(rfirst, n, rd_first);
268 }
269 }
270}
271
272template <typename T>
274{
275 T t;
276 T *operator->() noexcept { return &t; }
277};
278
279template <typename Iterator>
282 bool>::type;
283
284template <typename Iterator>
287 bool>::type;
288
289template <typename Iterator>
292 bool>::type;
293
294template <typename Container,
295 typename InputIterator,
296 IfIsNotForwardIterator<InputIterator> = true>
297void reserveIfForwardIterator(Container *, InputIterator, InputIterator)
298{
299}
300
301template <typename Container,
302 typename ForwardIterator,
303 IfIsForwardIterator<ForwardIterator> = true>
304void reserveIfForwardIterator(Container *c, ForwardIterator f, ForwardIterator l)
305{
306 c->reserve(static_cast<typename Container::size_type>(std::distance(f, l)));
307}
308
309template <typename Iterator>
310using KeyAndValueTest = decltype(
311 std::declval<Iterator &>().key(),
312 std::declval<Iterator &>().value()
313);
314
315template <typename Iterator>
316using FirstAndSecondTest = decltype(
317 (*std::declval<Iterator &>()).first,
318 (*std::declval<Iterator &>()).second
319);
320
321template <typename Iterator>
324
325template <typename Iterator>
331 >, bool>;
332
333template <typename Iterator>
334using MoveBackwardsTest = decltype(
335 std::declval<Iterator &>().operator--()
336);
337
338template <typename Iterator>
341
342template <typename T, typename U>
344 typename std::enable_if<!std::is_same<T, U>::value, bool>::type;
345
346template<typename T, typename U>
348
349template <typename Container, typename Predicate>
350auto sequential_erase_if(Container &c, Predicate &pred)
351{
352 // This is remove_if() modified to perform the find_if step on
353 // const_iterators to avoid shared container detaches if nothing needs to
354 // be removed. We cannot run remove_if after find_if: doing so would apply
355 // the predicate to the first matching element twice!
356
357 const auto cbegin = c.cbegin();
358 const auto cend = c.cend();
359 const auto t_it = std::find_if(cbegin, cend, pred);
360 auto result = std::distance(cbegin, t_it);
361 if (result == c.size())
362 return result - result; // `0` of the right type
363
364 // now detach:
365 const auto e = c.end();
366
367 auto it = std::next(c.begin(), result);
368 auto dest = it;
369
370 // Loop Invariants:
371 // - it != e
372 // - [next(it), e[ still to be checked
373 // - [c.begin(), dest[ are result
374 while (++it != e) {
375 if (!pred(*it)) {
376 *dest = std::move(*it);
377 ++dest;
378 }
379 }
380
381 result = std::distance(dest, e);
382 c.erase(dest, e);
383 return result;
384}
385
386template <typename Container, typename T>
387auto sequential_erase(Container &c, const T &t)
388{
389 // use the equivalence relation from http://eel.is/c++draft/list.erasure#1
390 auto cmp = [&](const auto &e) -> bool { return e == t; };
391 return sequential_erase_if(c, cmp); // can't pass rvalues!
392}
393
394template <typename Container, typename T>
395auto sequential_erase_with_copy(Container &c, const T &t)
396{
397 using CopyProxy = std::conditional_t<std::is_copy_constructible_v<T>, T, const T &>;
398 return sequential_erase(c, CopyProxy(t));
399}
400
401template <typename Container, typename T>
402auto sequential_erase_one(Container &c, const T &t)
403{
404 const auto cend = c.cend();
405 const auto it = std::find(c.cbegin(), cend, t);
406 if (it == cend)
407 return false;
408 c.erase(it);
409 return true;
410}
411
412template <typename String, typename Predicate>
413qsizetype q_string_like_container_erase_if(String &str, Predicate pred)
414{
415 auto &d = str.data_ptr();
416 qsizetype result = 0;
417 if (d.size == 0)
418 return result;
419
420 if (!d.needsDetach()) {
421 auto end = d.end();
422 auto it = std::remove_if(d.begin(), end, pred);
423 if (it != end) {
424 result = std::distance(it, end);
425 d->erase(it, result);
426 d.data()[d.size] = '\0';
427 }
428 } else {
429 const auto begin = d.begin();
430 const auto end = d.end();
431 auto it = std::find_if(begin, end, pred);
432 if (it == end)
433 return result;
434
435 String copy{d.size, Qt::Uninitialized};
436 auto &other_d = copy.data_ptr();
437 Q_CHECK_PTR(other_d.data());
438 auto dest = other_d.begin();
439 // std::uninitialized_copy will fallback to ::memcpy/memmove()
440 dest = std::uninitialized_copy(begin, it, dest);
441 dest = q_uninitialized_remove_copy_if(std::next(it), end, dest, pred);
442 other_d.size = std::distance(other_d.data(), dest);
443 other_d.data()[other_d.size] = '\0';
444 result = d.size - other_d.size;
445 str.swap(copy);
446 }
447
448 return result;
449}
450
451template <typename T, typename Predicate>
452qsizetype qset_erase_if(QSet<T> &set, Predicate &pred)
453{
454 qsizetype result = 0;
455 auto it = set.cbegin();
456 auto e = set.cend(); // stable across detach (QHash::end() is a stateless sentinel)...
457 while (it != e) {
458 if (pred(*it)) {
459 ++result;
460 it = set.erase(it);
461 e = set.cend(); // ...but re-set nonetheless, in case at some point it won't be
462 } else {
463 ++it;
464 }
465 }
466 return result;
467}
468
469
470// Prerequisite: F is invocable on ArgTypes
471template <typename R, typename F, typename ... ArgTypes>
474
475// is_invocable_r checks for implicit conversions, but we need to check
476// for explicit conversions in remove_if. So, roll our own trait.
477template <typename R, typename F, typename ... ArgTypes>
478constexpr bool is_invocable_explicit_r_v = std::conjunction_v<
479 std::is_invocable<F, ArgTypes...>,
481>;
482
483template <typename Container, typename Predicate>
484auto associative_erase_if(Container &c, Predicate &pred)
485{
486 // we support predicates callable with either Container::iterator
487 // or with std::pair<const Key &, Value &>
488 using Iterator = typename Container::iterator;
489 using Key = typename Container::key_type;
490 using Value = typename Container::mapped_type;
491 using KeyValuePair = std::pair<const Key &, Value &>;
492
493 typename Container::size_type result = 0;
494
495 auto it = c.begin();
496 const auto e = c.end();
497 while (it != e) {
498 if constexpr (is_invocable_explicit_r_v<bool, Predicate &, Iterator &>) {
499 if (pred(it)) {
500 it = c.erase(it);
501 ++result;
502 } else {
503 ++it;
504 }
505 } else if constexpr (is_invocable_explicit_r_v<bool, Predicate &, KeyValuePair &&>) {
506 KeyValuePair p(it.key(), it.value());
507 if (pred(std::move(p))) {
508 it = c.erase(it);
509 ++result;
510 } else {
511 ++it;
512 }
513 } else {
514 static_assert(type_dependent_false<Container>(), "Predicate has an incompatible signature");
515 }
516 }
517
518 return result;
519}
520
521} // namespace QtPrivate
522
523QT_END_NAMESPACE
524
525#endif // QCONTAINERTOOLS_IMPL_H
\inmodule QtCore
auto associative_erase_if(Container &c, Predicate &pred)
void q_uninitialized_relocate_n(T *first, N n, T *out)
qsizetype qset_erase_if(QSet< T > &set, Predicate &pred)
auto sequential_erase_one(Container &c, const T &t)
void q_relocate_overlap_n_left_move(iterator first, N n, iterator d_first)
auto sequential_erase_if(Container &c, Predicate &pred)
auto sequential_erase_with_copy(Container &c, const T &t)
constexpr bool q_points_into_range(const T &p, const C &c) noexcept
auto sequential_erase(Container &c, const T &t)
T * q_uninitialized_remove_copy_if(T *first, T *last, T *out, Predicate &pred)
qsizetype q_string_like_container_erase_if(String &str, Predicate pred)
constexpr bool q_points_into_range(const T *p, const T *b, const T *e)
void q_relocate_overlap_n(T *first, N n, T *d_first)
void reserveIfForwardIterator(Container *, InputIterator, InputIterator)
constexpr bool is_invocable_explicit_r_v
#define __has_include(x)
QByteArray qParseHtmlMetaForEncoding(QByteArrayView data)
static bool nameMatch(const char *a, QAnyStringView b)
static const uchar utf8bom[]
static QChar * fromUtf32LE(QChar *out, QByteArrayView in, QStringConverter::State *state)
@ HeaderDone
static QChar * fromUtf16LE(QChar *out, QByteArrayView in, QStringConverter::State *state)
static QChar * fromUtf32BE(QChar *out, QByteArrayView in, QStringConverter::State *state)
static qsizetype toUtf8Len(qsizetype l)
static QChar * fromLocal8Bit(QChar *out, QByteArrayView in, QStringConverter::State *state)
static QChar * fromUtf16(QChar *out, QByteArrayView in, QStringConverter::State *state)
static qsizetype toLatin1Len(qsizetype l)
static bool nameMatch_impl_impl(const char *a, const Char *b, const Char *b_end)
static bool nameMatch_impl(const char *a, QLatin1StringView b)
ConversionDirection
static QChar * fromUtf32(QChar *out, QByteArrayView in, QStringConverter::State *state)
static char * toUtf32(char *out, QStringView in, QStringConverter::State *state)
static char * toUtf16LE(char *out, QStringView in, QStringConverter::State *state)
static qsizetype fromUtf8Len(qsizetype l)
static char * toLocal8Bit(char *out, QStringView in, QStringConverter::State *state)
static qsizetype toUtf16Len(qsizetype l)
static qsizetype fromLatin1Len(qsizetype l)
static char * toUtf16BE(char *out, QStringView in, QStringConverter::State *state)
static char * toUtf32LE(char *out, QStringView in, QStringConverter::State *state)
static int partiallyParsedDataCount(QStringConverter::State *state)
static qsizetype fromUtf32Len(qsizetype l)
static qsizetype availableCodecCount()
static QChar * fromUtf16BE(QChar *out, QByteArrayView in, QStringConverter::State *state)
static qsizetype toUtf32Len(qsizetype l)
static char * toUtf16(char *out, QStringView in, QStringConverter::State *state)
static qsizetype fromUtf16Len(qsizetype l)
static char * toUtf32BE(char *out, QStringView in, QStringConverter::State *state)
static void appendUtf16(const NoOutput &, char16_t)
static void appendUcs4(const NoOutput &, char32_t)