1/****************************************************************************
2**
3** Copyright (C) 2016 The Qt Company Ltd.
4** Contact: https://www.qt.io/licensing/
5**
6** This file is part of the QtCore module of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:LGPL$
9** Commercial License Usage
10** Licensees holding valid commercial Qt licenses may use this file in
11** accordance with the commercial license agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and The Qt Company. For licensing terms
14** and conditions see https://www.qt.io/terms-conditions. For further
15** information use the contact form at https://www.qt.io/contact-us.
16**
17** GNU Lesser General Public License Usage
18** Alternatively, this file may be used under the terms of the GNU Lesser
19** General Public License version 3 as published by the Free Software
20** Foundation and appearing in the file LICENSE.LGPL3 included in the
21** packaging of this file. Please review the following information to
22** ensure the GNU Lesser General Public License version 3 requirements
23** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
24**
25** GNU General Public License Usage
26** Alternatively, this file may be used under the terms of the GNU
27** General Public License version 2.0 or (at your option) the GNU General
28** Public license version 3 or any later version approved by the KDE Free
29** Qt Foundation. The licenses are as published by the Free Software
30** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
31** included in the packaging of this file. Please review the following
32** information to ensure the GNU General Public License requirements will
33** be met: https://www.gnu.org/licenses/gpl-2.0.html and
34** https://www.gnu.org/licenses/gpl-3.0.html.
35**
36** $QT_END_LICENSE$
37**
38****************************************************************************/
39
40#ifndef QVECTOR_H
41#define QVECTOR_H
42
43#include <QtCore/qalgorithms.h>
44#include <QtCore/qiterator.h>
45#include <QtCore/qlist.h>
46#include <QtCore/qrefcount.h>
47#include <QtCore/qarraydata.h>
48#include <QtCore/qhashfunctions.h>
49
50#include <iterator>
51#include <vector>
52#include <stdlib.h>
53#include <string.h>
54#ifdef Q_COMPILER_INITIALIZER_LISTS
55#include <initializer_list>
56#endif
57
58#include <algorithm>
59
60QT_BEGIN_NAMESPACE
61
62template <typename T>
63class QVector
64{
65 typedef QTypedArrayData<T> Data;
66 Data *d;
67
68public:
69 inline QVector() Q_DECL_NOTHROW : d(Data::sharedNull()) { }
70 explicit QVector(int size);
71 QVector(int size, const T &t);
72 inline QVector(const QVector<T> &v);
73 inline ~QVector() { if (!d->ref.deref()) freeData(d); }
74 QVector<T> &operator=(const QVector<T> &v);
75#if defined(Q_COMPILER_RVALUE_REFS) || defined(Q_CLANG_QDOC)
76 QVector(QVector<T> &&other) Q_DECL_NOTHROW : d(other.d) { other.d = Data::sharedNull(); }
77 QVector<T> &operator=(QVector<T> &&other) Q_DECL_NOTHROW
78 { QVector moved(std::move(other)); swap(moved); return *this; }
79#endif
80 void swap(QVector<T> &other) Q_DECL_NOTHROW { qSwap(d, other.d); }
81#ifdef Q_COMPILER_INITIALIZER_LISTS
82 inline QVector(std::initializer_list<T> args);
83#endif
84 bool operator==(const QVector<T> &v) const;
85 inline bool operator!=(const QVector<T> &v) const { return !(*this == v); }
86
87 inline int size() const { return d->size; }
88
89 inline bool isEmpty() const { return d->size == 0; }
90
91 void resize(int size);
92
93 inline int capacity() const { return int(d->alloc); }
94 void reserve(int size);
95 inline void squeeze()
96 {
97 reallocData(d->size, d->size);
98 if (d->capacityReserved) {
99 // capacity reserved in a read only memory would be useless
100 // this checks avoid writing to such memory.
101 d->capacityReserved = 0;
102 }
103 }
104
105 inline void detach();
106 inline bool isDetached() const { return !d->ref.isShared(); }
107#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
108 inline void setSharable(bool sharable)
109 {
110 if (sharable == d->ref.isSharable())
111 return;
112 if (!sharable)
113 detach();
114
115 if (d == Data::unsharableEmpty()) {
116 if (sharable)
117 d = Data::sharedNull();
118 } else {
119 d->ref.setSharable(sharable);
120 }
121 Q_ASSERT(d->ref.isSharable() == sharable);
122 }
123#endif
124
125 inline bool isSharedWith(const QVector<T> &other) const { return d == other.d; }
126
127 inline T *data() { detach(); return d->begin(); }
128 inline const T *data() const { return d->begin(); }
129 inline const T *constData() const { return d->begin(); }
130 void clear();
131
132 const T &at(int i) const;
133 T &operator[](int i);
134 const T &operator[](int i) const;
135 void append(const T &t);
136#if defined(Q_COMPILER_RVALUE_REFS) || defined(Q_CLANG_QDOC)
137 void append(T &&t);
138#endif
139 inline void append(const QVector<T> &l) { *this += l; }
140 void prepend(T &&t);
141 void prepend(const T &t);
142 void insert(int i, T &&t);
143 void insert(int i, const T &t);
144 void insert(int i, int n, const T &t);
145 void replace(int i, const T &t);
146 void remove(int i);
147 void remove(int i, int n);
148 inline void removeFirst() { Q_ASSERT(!isEmpty()); erase(d->begin()); }
149 inline void removeLast();
150 T takeFirst() { Q_ASSERT(!isEmpty()); T r = std::move(first()); removeFirst(); return r; }
151 T takeLast() { Q_ASSERT(!isEmpty()); T r = std::move(last()); removeLast(); return r; }
152
153 QVector<T> &fill(const T &t, int size = -1);
154
155 int indexOf(const T &t, int from = 0) const;
156 int lastIndexOf(const T &t, int from = -1) const;
157 bool contains(const T &t) const;
158 int count(const T &t) const;
159
160 // QList compatibility
161 void removeAt(int i) { remove(i); }
162 int removeAll(const T &t)
163 {
164 const const_iterator ce = this->cend(), cit = std::find(this->cbegin(), ce, t);
165 if (cit == ce)
166 return 0;
167 // next operation detaches, so ce, cit, t may become invalidated:
168 const T tCopy = t;
169 const int firstFoundIdx = std::distance(this->cbegin(), cit);
170 const iterator e = end(), it = std::remove(begin() + firstFoundIdx, e, tCopy);
171 const int result = std::distance(it, e);
172 erase(it, e);
173 return result;
174 }
175 bool removeOne(const T &t)
176 {
177 const int i = indexOf(t);
178 if (i < 0)
179 return false;
180 remove(i);
181 return true;
182 }
183 int length() const { return size(); }
184 T takeAt(int i) { T t = std::move((*this)[i]); remove(i); return t; }
185 void move(int from, int to)
186 {
187 Q_ASSERT_X(from >= 0 && from < size(), "QVector::move(int,int)", "'from' is out-of-range");
188 Q_ASSERT_X(to >= 0 && to < size(), "QVector::move(int,int)", "'to' is out-of-range");
189 if (from == to) // don't detach when no-op
190 return;
191 detach();
192 T * const b = d->begin();
193 if (from < to)
194 std::rotate(b + from, b + from + 1, b + to + 1);
195 else
196 std::rotate(b + to, b + from, b + from + 1);
197 }
198
199 // STL-style
200 typedef typename Data::iterator iterator;
201 typedef typename Data::const_iterator const_iterator;
202 typedef std::reverse_iterator<iterator> reverse_iterator;
203 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
204#if !defined(QT_STRICT_ITERATORS) || defined(Q_CLANG_QDOC)
205 inline iterator begin() { detach(); return d->begin(); }
206 inline const_iterator begin() const Q_DECL_NOTHROW { return d->constBegin(); }
207 inline const_iterator cbegin() const Q_DECL_NOTHROW { return d->constBegin(); }
208 inline const_iterator constBegin() const Q_DECL_NOTHROW { return d->constBegin(); }
209 inline iterator end() { detach(); return d->end(); }
210 inline const_iterator end() const Q_DECL_NOTHROW { return d->constEnd(); }
211 inline const_iterator cend() const Q_DECL_NOTHROW { return d->constEnd(); }
212 inline const_iterator constEnd() const Q_DECL_NOTHROW { return d->constEnd(); }
213#else
214 inline iterator begin(iterator = iterator()) { detach(); return d->begin(); }
215 inline const_iterator begin(const_iterator = const_iterator()) const Q_DECL_NOTHROW { return d->constBegin(); }
216 inline const_iterator cbegin(const_iterator = const_iterator()) const Q_DECL_NOTHROW { return d->constBegin(); }
217 inline const_iterator constBegin(const_iterator = const_iterator()) const Q_DECL_NOTHROW { return d->constBegin(); }
218 inline iterator end(iterator = iterator()) { detach(); return d->end(); }
219 inline const_iterator end(const_iterator = const_iterator()) const Q_DECL_NOTHROW { return d->constEnd(); }
220 inline const_iterator cend(const_iterator = const_iterator()) const Q_DECL_NOTHROW { return d->constEnd(); }
221 inline const_iterator constEnd(const_iterator = const_iterator()) const Q_DECL_NOTHROW { return d->constEnd(); }
222#endif
223 reverse_iterator rbegin() { return reverse_iterator(end()); }
224 reverse_iterator rend() { return reverse_iterator(begin()); }
225 const_reverse_iterator rbegin() const Q_DECL_NOTHROW { return const_reverse_iterator(end()); }
226 const_reverse_iterator rend() const Q_DECL_NOTHROW { return const_reverse_iterator(begin()); }
227 const_reverse_iterator crbegin() const Q_DECL_NOTHROW { return const_reverse_iterator(end()); }
228 const_reverse_iterator crend() const Q_DECL_NOTHROW { return const_reverse_iterator(begin()); }
229 iterator insert(iterator before, int n, const T &x);
230 inline iterator insert(iterator before, const T &x) { return insert(before, 1, x); }
231 inline iterator insert(iterator before, T &&x);
232 iterator erase(iterator begin, iterator end);
233 inline iterator erase(iterator pos) { return erase(pos, pos+1); }
234
235 // more Qt
236 inline int count() const { return d->size; }
237 inline T& first() { Q_ASSERT(!isEmpty()); return *begin(); }
238 inline const T &first() const { Q_ASSERT(!isEmpty()); return *begin(); }
239 inline const T &constFirst() const { Q_ASSERT(!isEmpty()); return *begin(); }
240 inline T& last() { Q_ASSERT(!isEmpty()); return *(end()-1); }
241 inline const T &last() const { Q_ASSERT(!isEmpty()); return *(end()-1); }
242 inline const T &constLast() const { Q_ASSERT(!isEmpty()); return *(end()-1); }
243 inline bool startsWith(const T &t) const { return !isEmpty() && first() == t; }
244 inline bool endsWith(const T &t) const { return !isEmpty() && last() == t; }
245 QVector<T> mid(int pos, int len = -1) const;
246
247 T value(int i) const;
248 T value(int i, const T &defaultValue) const;
249
250 // STL compatibility
251 typedef T value_type;
252 typedef value_type* pointer;
253 typedef const value_type* const_pointer;
254 typedef value_type& reference;
255 typedef const value_type& const_reference;
256 typedef qptrdiff difference_type;
257 typedef iterator Iterator;
258 typedef const_iterator ConstIterator;
259 typedef int size_type;
260 inline void push_back(const T &t) { append(t); }
261#if defined(Q_COMPILER_RVALUE_REFS) || defined(Q_CLANG_QDOC)
262 void push_back(T &&t) { append(std::move(t)); }
263 void push_front(T &&t) { prepend(std::move(t)); }
264#endif
265 inline void push_front(const T &t) { prepend(t); }
266 void pop_back() { removeLast(); }
267 void pop_front() { removeFirst(); }
268 inline bool empty() const
269 { return d->size == 0; }
270 inline T& front() { return first(); }
271 inline const_reference front() const { return first(); }
272 inline reference back() { return last(); }
273 inline const_reference back() const { return last(); }
274 void shrink_to_fit() { squeeze(); }
275
276 // comfort
277 QVector<T> &operator+=(const QVector<T> &l);
278 inline QVector<T> operator+(const QVector<T> &l) const
279 { QVector n = *this; n += l; return n; }
280 inline QVector<T> &operator+=(const T &t)
281 { append(t); return *this; }
282 inline QVector<T> &operator<< (const T &t)
283 { append(t); return *this; }
284 inline QVector<T> &operator<<(const QVector<T> &l)
285 { *this += l; return *this; }
286 inline QVector<T> &operator+=(T &&t)
287 { append(std::move(t)); return *this; }
288 inline QVector<T> &operator<<(T &&t)
289 { append(std::move(t)); return *this; }
290
291 QList<T> toList() const;
292
293 static QVector<T> fromList(const QList<T> &list);
294
295 static inline QVector<T> fromStdVector(const std::vector<T> &vector)
296 { QVector<T> tmp; tmp.reserve(int(vector.size())); std::copy(vector.begin(), vector.end(), std::back_inserter(tmp)); return tmp; }
297 inline std::vector<T> toStdVector() const
298 { return std::vector<T>(d->begin(), d->end()); }
299private:
300 // ### Qt6: remove const from int parameters
301 void reallocData(const int size, const int alloc, QArrayData::AllocationOptions options = QArrayData::Default);
302 void reallocData(const int sz) { reallocData(sz, d->alloc); }
303 void freeData(Data *d);
304 void defaultConstruct(T *from, T *to);
305 void copyConstruct(const T *srcFrom, const T *srcTo, T *dstFrom);
306 void destruct(T *from, T *to);
307 bool isValidIterator(const iterator &i) const
308 {
309 return (i <= d->end()) && (d->begin() <= i);
310 }
311 class AlignmentDummy { Data header; T array[1]; };
312};
313
314#ifdef Q_CC_MSVC
315// behavior change: an object of POD type constructed with an initializer of the form ()
316// will be default-initialized
317# pragma warning ( push )
318# pragma warning ( disable : 4345 )
319# pragma warning(disable : 4127) // conditional expression is constant
320#endif
321
322template <typename T>
323void QVector<T>::defaultConstruct(T *from, T *to)
324{
325 if (QTypeInfo<T>::isComplex) {
326 while (from != to) {
327 new (from++) T();
328 }
329 } else {
330 ::memset(static_cast<void *>(from), 0, (to - from) * sizeof(T));
331 }
332}
333
334template <typename T>
335void QVector<T>::copyConstruct(const T *srcFrom, const T *srcTo, T *dstFrom)
336{
337 if (QTypeInfo<T>::isComplex) {
338 while (srcFrom != srcTo)
339 new (dstFrom++) T(*srcFrom++);
340 } else {
341 ::memcpy(static_cast<void *>(dstFrom), static_cast<const void *>(srcFrom), (srcTo - srcFrom) * sizeof(T));
342 }
343}
344
345template <typename T>
346void QVector<T>::destruct(T *from, T *to)
347{
348 if (QTypeInfo<T>::isComplex) {
349 while (from != to) {
350 from++->~T();
351 }
352 }
353}
354
355template <typename T>
356inline QVector<T>::QVector(const QVector<T> &v)
357{
358 if (v.d->ref.ref()) {
359 d = v.d;
360 } else {
361 if (v.d->capacityReserved) {
362 d = Data::allocate(v.d->alloc);
363 Q_CHECK_PTR(d);
364 d->capacityReserved = true;
365 } else {
366 d = Data::allocate(v.d->size);
367 Q_CHECK_PTR(d);
368 }
369 if (d->alloc) {
370 copyConstruct(v.d->begin(), v.d->end(), d->begin());
371 d->size = v.d->size;
372 }
373 }
374}
375
376#if defined(Q_CC_MSVC)
377#pragma warning( pop )
378#endif
379
380template <typename T>
381void QVector<T>::detach()
382{
383 if (!isDetached()) {
384#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
385 if (!d->alloc)
386 d = Data::unsharableEmpty();
387 else
388#endif
389 reallocData(d->size, int(d->alloc));
390 }
391 Q_ASSERT(isDetached());
392}
393
394template <typename T>
395void QVector<T>::reserve(int asize)
396{
397 if (asize > int(d->alloc))
398 reallocData(d->size, asize);
399 if (isDetached()
400#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
401 && d != Data::unsharableEmpty()
402#endif
403 )
404 d->capacityReserved = 1;
405 Q_ASSERT(capacity() >= asize);
406}
407
408template <typename T>
409void QVector<T>::resize(int asize)
410{
411 int newAlloc;
412 const int oldAlloc = int(d->alloc);
413 QArrayData::AllocationOptions opt;
414
415 if (asize > oldAlloc) { // there is not enough space
416 newAlloc = asize;
417 opt = QArrayData::Grow;
418 } else {
419 newAlloc = oldAlloc;
420 }
421 reallocData(asize, newAlloc, opt);
422}
423template <typename T>
424inline void QVector<T>::clear()
425{ resize(0); }
426template <typename T>
427inline const T &QVector<T>::at(int i) const
428{ Q_ASSERT_X(i >= 0 && i < d->size, "QVector<T>::at", "index out of range");
429 return d->begin()[i]; }
430template <typename T>
431inline const T &QVector<T>::operator[](int i) const
432{ Q_ASSERT_X(i >= 0 && i < d->size, "QVector<T>::operator[]", "index out of range");
433 return d->begin()[i]; }
434template <typename T>
435inline T &QVector<T>::operator[](int i)
436{ Q_ASSERT_X(i >= 0 && i < d->size, "QVector<T>::operator[]", "index out of range");
437 return data()[i]; }
438template <typename T>
439inline void QVector<T>::insert(int i, const T &t)
440{ Q_ASSERT_X(i >= 0 && i <= d->size, "QVector<T>::insert", "index out of range");
441 insert(begin() + i, 1, t); }
442template <typename T>
443inline void QVector<T>::insert(int i, int n, const T &t)
444{ Q_ASSERT_X(i >= 0 && i <= d->size, "QVector<T>::insert", "index out of range");
445 insert(begin() + i, n, t); }
446template <typename T>
447inline void QVector<T>::insert(int i, T &&t)
448{ Q_ASSERT_X(i >= 0 && i <= d->size, "QVector<T>::insert", "index out of range");
449 insert(begin() + i, std::move(t)); }
450template <typename T>
451inline void QVector<T>::remove(int i, int n)
452{ Q_ASSERT_X(i >= 0 && n >= 0 && i + n <= d->size, "QVector<T>::remove", "index out of range");
453 erase(d->begin() + i, d->begin() + i + n); }
454template <typename T>
455inline void QVector<T>::remove(int i)
456{ Q_ASSERT_X(i >= 0 && i < d->size, "QVector<T>::remove", "index out of range");
457 erase(d->begin() + i, d->begin() + i + 1); }
458template <typename T>
459inline void QVector<T>::prepend(const T &t)
460{ insert(begin(), 1, t); }
461template <typename T>
462inline void QVector<T>::prepend(T &&t)
463{ insert(begin(), std::move(t)); }
464
465template <typename T>
466inline void QVector<T>::replace(int i, const T &t)
467{
468 Q_ASSERT_X(i >= 0 && i < d->size, "QVector<T>::replace", "index out of range");
469 const T copy(t);
470 data()[i] = copy;
471}
472
473template <typename T>
474QVector<T> &QVector<T>::operator=(const QVector<T> &v)
475{
476 if (v.d != d) {
477 QVector<T> tmp(v);
478 tmp.swap(*this);
479 }
480 return *this;
481}
482
483template <typename T>
484QVector<T>::QVector(int asize)
485{
486 Q_ASSERT_X(asize >= 0, "QVector::QVector", "Size must be greater than or equal to 0.");
487 if (Q_LIKELY(asize > 0)) {
488 d = Data::allocate(asize);
489 Q_CHECK_PTR(d);
490 d->size = asize;
491 defaultConstruct(d->begin(), d->end());
492 } else {
493 d = Data::sharedNull();
494 }
495}
496
497template <typename T>
498QVector<T>::QVector(int asize, const T &t)
499{
500 Q_ASSERT_X(asize >= 0, "QVector::QVector", "Size must be greater than or equal to 0.");
501 if (asize > 0) {
502 d = Data::allocate(asize);
503 Q_CHECK_PTR(d);
504 d->size = asize;
505 T* i = d->end();
506 while (i != d->begin())
507 new (--i) T(t);
508 } else {
509 d = Data::sharedNull();
510 }
511}
512
513#ifdef Q_COMPILER_INITIALIZER_LISTS
514# if defined(Q_CC_MSVC)
515QT_WARNING_PUSH
516QT_WARNING_DISABLE_MSVC(4127) // conditional expression is constant
517# endif // Q_CC_MSVC
518
519template <typename T>
520QVector<T>::QVector(std::initializer_list<T> args)
521{
522 if (args.size() > 0) {
523 d = Data::allocate(args.size());
524 Q_CHECK_PTR(d);
525 // std::initializer_list<T>::iterator is guaranteed to be
526 // const T* ([support.initlist]/1), so can be memcpy'ed away from by copyConstruct
527 copyConstruct(args.begin(), args.end(), d->begin());
528 d->size = int(args.size());
529 } else {
530 d = Data::sharedNull();
531 }
532}
533# if defined(Q_CC_MSVC)
534QT_WARNING_POP
535# endif // Q_CC_MSVC
536#endif // Q_COMPILER_INITALIZER_LISTS
537
538template <typename T>
539void QVector<T>::freeData(Data *x)
540{
541 destruct(x->begin(), x->end());
542 Data::deallocate(x);
543}
544
545#if defined(Q_CC_MSVC)
546QT_WARNING_PUSH
547QT_WARNING_DISABLE_MSVC(4127) // conditional expression is constant
548#endif
549
550template <typename T>
551void QVector<T>::reallocData(const int asize, const int aalloc, QArrayData::AllocationOptions options)
552{
553 Q_ASSERT(asize >= 0 && asize <= aalloc);
554 Data *x = d;
555
556 const bool isShared = d->ref.isShared();
557
558 if (aalloc != 0) {
559 if (aalloc != int(d->alloc) || isShared) {
560 QT_TRY {
561 // allocate memory
562 x = Data::allocate(aalloc, options);
563 Q_CHECK_PTR(x);
564 // aalloc is bigger then 0 so it is not [un]sharedEmpty
565#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
566 Q_ASSERT(x->ref.isSharable() || options.testFlag(QArrayData::Unsharable));
567#endif
568 Q_ASSERT(!x->ref.isStatic());
569 x->size = asize;
570
571 T *srcBegin = d->begin();
572 T *srcEnd = asize > d->size ? d->end() : d->begin() + asize;
573 T *dst = x->begin();
574
575 if (!QTypeInfoQuery<T>::isRelocatable || (isShared && QTypeInfo<T>::isComplex)) {
576 QT_TRY {
577 if (isShared || !std::is_nothrow_move_constructible<T>::value) {
578 // we can not move the data, we need to copy construct it
579 while (srcBegin != srcEnd)
580 new (dst++) T(*srcBegin++);
581 } else {
582 while (srcBegin != srcEnd)
583 new (dst++) T(std::move(*srcBegin++));
584 }
585 } QT_CATCH (...) {
586 // destruct already copied objects
587 destruct(x->begin(), dst);
588 QT_RETHROW;
589 }
590 } else {
591 ::memcpy(static_cast<void *>(dst), static_cast<void *>(srcBegin), (srcEnd - srcBegin) * sizeof(T));
592 dst += srcEnd - srcBegin;
593
594 // destruct unused / not moved data
595 if (asize < d->size)
596 destruct(d->begin() + asize, d->end());
597 }
598
599 if (asize > d->size) {
600 // construct all new objects when growing
601 if (!QTypeInfo<T>::isComplex) {
602 ::memset(static_cast<void *>(dst), 0, (static_cast<T *>(x->end()) - dst) * sizeof(T));
603 } else {
604 QT_TRY {
605 while (dst != x->end())
606 new (dst++) T();
607 } QT_CATCH (...) {
608 // destruct already copied objects
609 destruct(x->begin(), dst);
610 QT_RETHROW;
611 }
612 }
613 }
614 } QT_CATCH (...) {
615 Data::deallocate(x);
616 QT_RETHROW;
617 }
618 x->capacityReserved = d->capacityReserved;
619 } else {
620 Q_ASSERT(int(d->alloc) == aalloc); // resize, without changing allocation size
621 Q_ASSERT(isDetached()); // can be done only on detached d
622 Q_ASSERT(x == d); // in this case we do not need to allocate anything
623 if (asize <= d->size) {
624 destruct(x->begin() + asize, x->end()); // from future end to current end
625 } else {
626 defaultConstruct(x->end(), x->begin() + asize); // from current end to future end
627 }
628 x->size = asize;
629 }
630 } else {
631 x = Data::sharedNull();
632 }
633 if (d != x) {
634 if (!d->ref.deref()) {
635 if (!QTypeInfoQuery<T>::isRelocatable || !aalloc || (isShared && QTypeInfo<T>::isComplex)) {
636 // data was copy constructed, we need to call destructors
637 // or if !alloc we did nothing to the old 'd'.
638 freeData(d);
639 } else {
640 Data::deallocate(d);
641 }
642 }
643 d = x;
644 }
645
646 Q_ASSERT(d->data());
647 Q_ASSERT(uint(d->size) <= d->alloc);
648#if !defined(QT_NO_UNSHARABLE_CONTAINERS)
649 Q_ASSERT(d != Data::unsharableEmpty());
650#endif
651 Q_ASSERT(aalloc ? d != Data::sharedNull() : d == Data::sharedNull());
652 Q_ASSERT(d->alloc >= uint(aalloc));
653 Q_ASSERT(d->size == asize);
654}
655
656#if defined(Q_CC_MSVC)
657QT_WARNING_POP
658#endif
659
660template<typename T>
661Q_OUTOFLINE_TEMPLATE T QVector<T>::value(int i) const
662{
663 if (uint(i) >= uint(d->size)) {
664 return T();
665 }
666 return d->begin()[i];
667}
668template<typename T>
669Q_OUTOFLINE_TEMPLATE T QVector<T>::value(int i, const T &defaultValue) const
670{
671 return uint(i) >= uint(d->size) ? defaultValue : d->begin()[i];
672}
673
674template <typename T>
675void QVector<T>::append(const T &t)
676{
677 const bool isTooSmall = uint(d->size + 1) > d->alloc;
678 if (!isDetached() || isTooSmall) {
679 T copy(t);
680 QArrayData::AllocationOptions opt(isTooSmall ? QArrayData::Grow : QArrayData::Default);
681 reallocData(d->size, isTooSmall ? d->size + 1 : d->alloc, opt);
682
683 if (QTypeInfo<T>::isComplex)
684 new (d->end()) T(qMove(copy));
685 else
686 *d->end() = qMove(copy);
687
688 } else {
689 if (QTypeInfo<T>::isComplex)
690 new (d->end()) T(t);
691 else
692 *d->end() = t;
693 }
694 ++d->size;
695}
696
697#ifdef Q_COMPILER_RVALUE_REFS
698template <typename T>
699void QVector<T>::append(T &&t)
700{
701 const bool isTooSmall = uint(d->size + 1) > d->alloc;
702 if (!isDetached() || isTooSmall) {
703 QArrayData::AllocationOptions opt(isTooSmall ? QArrayData::Grow : QArrayData::Default);
704 reallocData(d->size, isTooSmall ? d->size + 1 : d->alloc, opt);
705 }
706
707 new (d->end()) T(std::move(t));
708
709 ++d->size;
710}
711#endif
712
713template <typename T>
714void QVector<T>::removeLast()
715{
716 Q_ASSERT(!isEmpty());
717 Q_ASSERT(d->alloc);
718
719 if (!d->ref.isShared()) {
720 --d->size;
721 if (QTypeInfo<T>::isComplex)
722 (d->data() + d->size)->~T();
723 } else {
724 reallocData(d->size - 1);
725 }
726}
727
728template <typename T>
729typename QVector<T>::iterator QVector<T>::insert(iterator before, size_type n, const T &t)
730{
731 Q_ASSERT_X(isValidIterator(before), "QVector::insert", "The specified iterator argument 'before' is invalid");
732
733 const auto offset = std::distance(d->begin(), before);
734 if (n != 0) {
735 const T copy(t);
736 if (!isDetached() || d->size + n > int(d->alloc))
737 reallocData(d->size, d->size + n, QArrayData::Grow);
738 if (!QTypeInfoQuery<T>::isRelocatable) {
739 T *b = d->end();
740 T *i = d->end() + n;
741 while (i != b)
742 new (--i) T;
743 i = d->end();
744 T *j = i + n;
745 b = d->begin() + offset;
746 while (i != b)
747 *--j = *--i;
748 i = b+n;
749 while (i != b)
750 *--i = copy;
751 } else {
752 T *b = d->begin() + offset;
753 T *i = b + n;
754 memmove(static_cast<void *>(i), static_cast<const void *>(b), (d->size - offset) * sizeof(T));
755 while (i != b)
756 new (--i) T(copy);
757 }
758 d->size += n;
759 }
760 return d->begin() + offset;
761}
762
763template <typename T>
764typename QVector<T>::iterator QVector<T>::insert(iterator before, T &&t)
765{
766 Q_ASSERT_X(isValidIterator(before), "QVector::insert", "The specified iterator argument 'before' is invalid");
767
768 const auto offset = std::distance(d->begin(), before);
769 if (!isDetached() || d->size + 1 > int(d->alloc))
770 reallocData(d->size, d->size + 1, QArrayData::Grow);
771 if (!QTypeInfoQuery<T>::isRelocatable) {
772 T *i = d->end();
773 T *j = i + 1;
774 T *b = d->begin() + offset;
775 // The new end-element needs to be constructed, the rest must be move assigned
776 if (i != b) {
777 new (--j) T(std::move(*--i));
778 while (i != b)
779 *--j = std::move(*--i);
780 *b = std::move(t);
781 } else {
782 new (b) T(std::move(t));
783 }
784 } else {
785 T *b = d->begin() + offset;
786 memmove(static_cast<void *>(b + 1), static_cast<const void *>(b), (d->size - offset) * sizeof(T));
787 new (b) T(std::move(t));
788 }
789 d->size += 1;
790 return d->begin() + offset;
791}
792
793template <typename T>
794typename QVector<T>::iterator QVector<T>::erase(iterator abegin, iterator aend)
795{
796 Q_ASSERT_X(isValidIterator(abegin), "QVector::erase", "The specified iterator argument 'abegin' is invalid");
797 Q_ASSERT_X(isValidIterator(aend), "QVector::erase", "The specified iterator argument 'aend' is invalid");
798
799 const auto itemsToErase = aend - abegin;
800
801 if (!itemsToErase)
802 return abegin;
803
804 Q_ASSERT(abegin >= d->begin());
805 Q_ASSERT(aend <= d->end());
806 Q_ASSERT(abegin <= aend);
807
808 const auto itemsUntouched = abegin - d->begin();
809
810 // FIXME we could do a proper realloc, which copy constructs only needed data.
811 // FIXME we are about to delete data - maybe it is good time to shrink?
812 // FIXME the shrink is also an issue in removeLast, that is just a copy + reduce of this.
813 if (d->alloc) {
814 detach();
815 abegin = d->begin() + itemsUntouched;
816 aend = abegin + itemsToErase;
817 if (!QTypeInfoQuery<T>::isRelocatable) {
818 iterator moveBegin = abegin + itemsToErase;
819 iterator moveEnd = d->end();
820 while (moveBegin != moveEnd) {
821 if (QTypeInfo<T>::isComplex)
822 static_cast<T *>(abegin)->~T();
823 new (abegin++) T(*moveBegin++);
824 }
825 if (abegin < d->end()) {
826 // destroy rest of instances
827 destruct(abegin, d->end());
828 }
829 } else {
830 destruct(abegin, aend);
831 // QTBUG-53605: static_cast<void *> masks clang errors of the form
832 // error: destination for this 'memmove' call is a pointer to class containing a dynamic class
833 // FIXME maybe use std::is_polymorphic (as soon as allowed) to avoid the memmove
834 memmove(static_cast<void *>(abegin), static_cast<void *>(aend),
835 (d->size - itemsToErase - itemsUntouched) * sizeof(T));
836 }
837 d->size -= int(itemsToErase);
838 }
839 return d->begin() + itemsUntouched;
840}
841
842template <typename T>
843bool QVector<T>::operator==(const QVector<T> &v) const
844{
845 if (d == v.d)
846 return true;
847 if (d->size != v.d->size)
848 return false;
849 const T *vb = v.d->begin();
850 const T *b = d->begin();
851 const T *e = d->end();
852 return std::equal(b, e, QT_MAKE_CHECKED_ARRAY_ITERATOR(vb, v.d->size));
853}
854
855template <typename T>
856QVector<T> &QVector<T>::fill(const T &from, int asize)
857{
858 const T copy(from);
859 resize(asize < 0 ? d->size : asize);
860 if (d->size) {
861 T *i = d->end();
862 T *b = d->begin();
863 while (i != b)
864 *--i = copy;
865 }
866 return *this;
867}
868
869template <typename T>
870QVector<T> &QVector<T>::operator+=(const QVector &l)
871{
872 if (d == Data::sharedNull()) {
873 *this = l;
874 } else {
875 uint newSize = d->size + l.d->size;
876 const bool isTooSmall = newSize > d->alloc;
877 if (!isDetached() || isTooSmall) {
878 QArrayData::AllocationOptions opt(isTooSmall ? QArrayData::Grow : QArrayData::Default);
879 reallocData(d->size, isTooSmall ? newSize : d->alloc, opt);
880 }
881
882 if (d->alloc) {
883 T *w = d->begin() + newSize;
884 T *i = l.d->end();
885 T *b = l.d->begin();
886 while (i != b) {
887 if (QTypeInfo<T>::isComplex)
888 new (--w) T(*--i);
889 else
890 *--w = *--i;
891 }
892 d->size = newSize;
893 }
894 }
895 return *this;
896}
897
898template <typename T>
899int QVector<T>::indexOf(const T &t, int from) const
900{
901 if (from < 0)
902 from = qMax(from + d->size, 0);
903 if (from < d->size) {
904 T* n = d->begin() + from - 1;
905 T* e = d->end();
906 while (++n != e)
907 if (*n == t)
908 return n - d->begin();
909 }
910 return -1;
911}
912
913template <typename T>
914int QVector<T>::lastIndexOf(const T &t, int from) const
915{
916 if (from < 0)
917 from += d->size;
918 else if (from >= d->size)
919 from = d->size-1;
920 if (from >= 0) {
921 T* b = d->begin();
922 T* n = d->begin() + from + 1;
923 while (n != b) {
924 if (*--n == t)
925 return n - b;
926 }
927 }
928 return -1;
929}
930
931template <typename T>
932bool QVector<T>::contains(const T &t) const
933{
934 const T *b = d->begin();
935 const T *e = d->end();
936 return std::find(b, e, t) != e;
937}
938
939template <typename T>
940int QVector<T>::count(const T &t) const
941{
942 const T *b = d->begin();
943 const T *e = d->end();
944 return int(std::count(b, e, t));
945}
946
947template <typename T>
948Q_OUTOFLINE_TEMPLATE QVector<T> QVector<T>::mid(int pos, int len) const
949{
950 using namespace QtPrivate;
951 switch (QContainerImplHelper::mid(d->size, &pos, &len)) {
952 case QContainerImplHelper::Null:
953 case QContainerImplHelper::Empty:
954 return QVector<T>();
955 case QContainerImplHelper::Full:
956 return *this;
957 case QContainerImplHelper::Subset:
958 break;
959 }
960
961 QVector<T> midResult;
962 midResult.reallocData(0, len);
963 T *srcFrom = d->begin() + pos;
964 T *srcTo = d->begin() + pos + len;
965 midResult.copyConstruct(srcFrom, srcTo, midResult.data());
966 midResult.d->size = len;
967 return midResult;
968}
969
970template <typename T>
971Q_OUTOFLINE_TEMPLATE QList<T> QVector<T>::toList() const
972{
973 QList<T> result;
974 result.reserve(size());
975 for (int i = 0; i < size(); ++i)
976 result.append(at(i));
977 return result;
978}
979
980template <typename T>
981Q_OUTOFLINE_TEMPLATE QVector<T> QList<T>::toVector() const
982{
983 QVector<T> result(size());
984 for (int i = 0; i < size(); ++i)
985 result[i] = at(i);
986 return result;
987}
988
989template <typename T>
990QVector<T> QVector<T>::fromList(const QList<T> &list)
991{
992 return list.toVector();
993}
994
995template <typename T>
996QList<T> QList<T>::fromVector(const QVector<T> &vector)
997{
998 return vector.toList();
999}
1000
1001Q_DECLARE_SEQUENTIAL_ITERATOR(Vector)
1002Q_DECLARE_MUTABLE_SEQUENTIAL_ITERATOR(Vector)
1003
1004template <typename T>
1005uint qHash(const QVector<T> &key, uint seed = 0)
1006 Q_DECL_NOEXCEPT_EXPR(noexcept(qHashRange(key.cbegin(), key.cend(), seed)))
1007{
1008 return qHashRange(key.cbegin(), key.cend(), seed);
1009}
1010
1011template <typename T>
1012bool operator<(const QVector<T> &lhs, const QVector<T> &rhs)
1013 Q_DECL_NOEXCEPT_EXPR(noexcept(std::lexicographical_compare(lhs.begin(), lhs.end(),
1014 rhs.begin(), rhs.end())))
1015{
1016 return std::lexicographical_compare(lhs.begin(), lhs.end(),
1017 rhs.begin(), rhs.end());
1018}
1019
1020template <typename T>
1021inline bool operator>(const QVector<T> &lhs, const QVector<T> &rhs)
1022 Q_DECL_NOEXCEPT_EXPR(noexcept(lhs < rhs))
1023{
1024 return rhs < lhs;
1025}
1026
1027template <typename T>
1028inline bool operator<=(const QVector<T> &lhs, const QVector<T> &rhs)
1029 Q_DECL_NOEXCEPT_EXPR(noexcept(lhs < rhs))
1030{
1031 return !(lhs > rhs);
1032}
1033
1034template <typename T>
1035inline bool operator>=(const QVector<T> &lhs, const QVector<T> &rhs)
1036 Q_DECL_NOEXCEPT_EXPR(noexcept(lhs < rhs))
1037{
1038 return !(lhs < rhs);
1039}
1040
1041/*
1042 ### Qt 5:
1043 ### This needs to be removed for next releases of Qt. It is a workaround for vc++ because
1044 ### Qt exports QPolygon and QPolygonF that inherit QVector<QPoint> and
1045 ### QVector<QPointF> respectively.
1046*/
1047
1048#ifdef Q_CC_MSVC
1049QT_BEGIN_INCLUDE_NAMESPACE
1050#include <QtCore/qpoint.h>
1051QT_END_INCLUDE_NAMESPACE
1052
1053#ifndef Q_TEMPLATE_EXTERN
1054#if defined(QT_BUILD_CORE_LIB)
1055#define Q_TEMPLATE_EXTERN
1056#else
1057#define Q_TEMPLATE_EXTERN extern
1058#endif
1059#endif
1060Q_TEMPLATE_EXTERN template class Q_CORE_EXPORT QVector<QPointF>;
1061Q_TEMPLATE_EXTERN template class Q_CORE_EXPORT QVector<QPoint>;
1062#endif
1063
1064QVector<uint> QStringView::toUcs4() const { return QtPrivate::convertToUcs4(*this); }
1065
1066QT_END_NAMESPACE
1067
1068#endif // QVECTOR_H
1069