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