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