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 QVARLENGTHARRAY_H
41#define QVARLENGTHARRAY_H
42
43#include <QtCore/qcontainerfwd.h>
44#include <QtCore/qglobal.h>
45#include <QtCore/qalgorithms.h>
46#include <QtCore/qcontainertools_impl.h>
47#include <QtCore/qhashfunctions.h>
48
49#include <algorithm>
50#include <initializer_list>
51#include <iterator>
52#include <new>
53#include <string.h>
54#include <stdlib.h>
55
56QT_BEGIN_NAMESPACE
57
58
59// Prealloc = 256 by default, specified in qcontainerfwd.h
60template<class T, int Prealloc>
61class QVarLengthArray
62{
63public:
64 QVarLengthArray() : QVarLengthArray(0) {}
65
66 inline explicit QVarLengthArray(int size);
67
68 inline QVarLengthArray(const QVarLengthArray<T, Prealloc> &other)
69 : a(Prealloc), s(0), ptr(reinterpret_cast<T *>(array))
70 {
71 append(other.constData(), other.size());
72 }
73
74 QVarLengthArray(std::initializer_list<T> args)
75 : QVarLengthArray(args.begin(), args.end())
76 {
77 }
78
79 template <typename InputIterator, QtPrivate::IfIsInputIterator<InputIterator> = true>
80 inline QVarLengthArray(InputIterator first, InputIterator last)
81 : QVarLengthArray()
82 {
83 QtPrivate::reserveIfForwardIterator(this, first, last);
84 std::copy(first, last, std::back_inserter(*this));
85 }
86
87 inline ~QVarLengthArray() {
88 if (QTypeInfo<T>::isComplex) {
89 T *i = ptr + s;
90 while (i-- != ptr)
91 i->~T();
92 }
93 if (ptr != reinterpret_cast<T *>(array))
94 free(ptr);
95 }
96 inline QVarLengthArray<T, Prealloc> &operator=(const QVarLengthArray<T, Prealloc> &other)
97 {
98 if (this != &other) {
99 clear();
100 append(other.constData(), other.size());
101 }
102 return *this;
103 }
104
105 QVarLengthArray<T, Prealloc> &operator=(std::initializer_list<T> list)
106 {
107 resize(list.size());
108 std::copy(list.begin(), list.end(),
109 QT_MAKE_CHECKED_ARRAY_ITERATOR(this->begin(), this->size()));
110 return *this;
111 }
112
113 inline void removeLast() {
114 Q_ASSERT(s > 0);
115 if (QTypeInfo<T>::isComplex)
116 ptr[s - 1].~T();
117 --s;
118 }
119 inline int size() const { return s; }
120 inline int count() const { return s; }
121 inline int length() const { return s; }
122 inline T& first() { Q_ASSERT(!isEmpty()); return *begin(); }
123 inline const T& first() const { Q_ASSERT(!isEmpty()); return *begin(); }
124 T& last() { Q_ASSERT(!isEmpty()); return *(end() - 1); }
125 const T& last() const { Q_ASSERT(!isEmpty()); return *(end() - 1); }
126 inline bool isEmpty() const { return (s == 0); }
127 inline void resize(int size);
128 inline void clear() { resize(0); }
129 inline void squeeze();
130
131 inline int capacity() const { return a; }
132 inline void reserve(int size);
133
134 inline int indexOf(const T &t, int from = 0) const;
135 inline int lastIndexOf(const T &t, int from = -1) const;
136 inline bool contains(const T &t) const;
137
138 inline T &operator[](int idx) {
139 Q_ASSERT(idx >= 0 && idx < s);
140 return ptr[idx];
141 }
142 inline const T &operator[](int idx) const {
143 Q_ASSERT(idx >= 0 && idx < s);
144 return ptr[idx];
145 }
146 inline const T &at(int idx) const { return operator[](idx); }
147
148 T value(int i) const;
149 T value(int i, const T &defaultValue) const;
150
151 inline void append(const T &t) {
152 if (s == a) { // i.e. s != 0
153 T copy(t);
154 realloc(s, s<<1);
155 const int idx = s++;
156 if (QTypeInfo<T>::isComplex) {
157 new (ptr + idx) T(std::move(copy));
158 } else {
159 ptr[idx] = std::move(copy);
160 }
161 } else {
162 const int idx = s++;
163 if (QTypeInfo<T>::isComplex) {
164 new (ptr + idx) T(t);
165 } else {
166 ptr[idx] = t;
167 }
168 }
169 }
170
171 void append(T &&t) {
172 if (s == a)
173 realloc(s, s << 1);
174 const int idx = s++;
175 if (QTypeInfo<T>::isComplex)
176 new (ptr + idx) T(std::move(t));
177 else
178 ptr[idx] = std::move(t);
179 }
180
181 void append(const T *buf, int size);
182 inline QVarLengthArray<T, Prealloc> &operator<<(const T &t)
183 { append(t); return *this; }
184 inline QVarLengthArray<T, Prealloc> &operator<<(T &&t)
185 { append(std::move(t)); return *this; }
186 inline QVarLengthArray<T, Prealloc> &operator+=(const T &t)
187 { append(t); return *this; }
188 inline QVarLengthArray<T, Prealloc> &operator+=(T &&t)
189 { append(std::move(t)); return *this; }
190
191 void prepend(T &&t);
192 void prepend(const T &t);
193 void insert(int i, T &&t);
194 void insert(int i, const T &t);
195 void insert(int i, int n, const T &t);
196 void replace(int i, const T &t);
197 void remove(int i);
198 void remove(int i, int n);
199
200
201 inline T *data() { return ptr; }
202 inline const T *data() const { return ptr; }
203 inline const T * constData() const { return ptr; }
204 typedef int size_type;
205 typedef T value_type;
206 typedef value_type *pointer;
207 typedef const value_type *const_pointer;
208 typedef value_type &reference;
209 typedef const value_type &const_reference;
210 typedef qptrdiff difference_type;
211
212
213 typedef T* iterator;
214 typedef const T* const_iterator;
215 typedef std::reverse_iterator<iterator> reverse_iterator;
216 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
217
218 inline iterator begin() { return ptr; }
219 inline const_iterator begin() const { return ptr; }
220 inline const_iterator cbegin() const { return ptr; }
221 inline const_iterator constBegin() const { return ptr; }
222 inline iterator end() { return ptr + s; }
223 inline const_iterator end() const { return ptr + s; }
224 inline const_iterator cend() const { return ptr + s; }
225 inline const_iterator constEnd() const { return ptr + s; }
226 reverse_iterator rbegin() { return reverse_iterator(end()); }
227 reverse_iterator rend() { return reverse_iterator(begin()); }
228 const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); }
229 const_reverse_iterator rend() const { return const_reverse_iterator(begin()); }
230 const_reverse_iterator crbegin() const { return const_reverse_iterator(end()); }
231 const_reverse_iterator crend() const { return const_reverse_iterator(begin()); }
232 iterator insert(const_iterator before, int n, const T &x);
233 iterator insert(const_iterator before, T &&x);
234 inline iterator insert(const_iterator before, const T &x) { return insert(before, 1, x); }
235 iterator erase(const_iterator begin, const_iterator end);
236 inline iterator erase(const_iterator pos) { return erase(pos, pos+1); }
237
238 // STL compatibility:
239 inline bool empty() const { return isEmpty(); }
240 inline void push_back(const T &t) { append(t); }
241 void push_back(T &&t) { append(std::move(t)); }
242 inline void pop_back() { removeLast(); }
243 inline T &front() { return first(); }
244 inline const T &front() const { return first(); }
245 inline T &back() { return last(); }
246 inline const T &back() const { return last(); }
247 void shrink_to_fit() { squeeze(); }
248
249private:
250 void realloc(int size, int alloc);
251
252 int a; // capacity
253 int s; // size
254 T *ptr; // data
255 union {
256 char array[Prealloc * sizeof(T)];
257 qint64 q_for_alignment_1;
258 double q_for_alignment_2;
259 };
260
261 bool isValidIterator(const const_iterator &i) const
262 {
263 const std::less<const T*> less = {};
264 return !less(cend(), i) && !less(i, cbegin());
265 }
266};
267
268template <class T, int Prealloc>
269Q_INLINE_TEMPLATE QVarLengthArray<T, Prealloc>::QVarLengthArray(int asize)
270 : s(asize) {
271 Q_STATIC_ASSERT_X(Prealloc > 0, "QVarLengthArray Prealloc must be greater than 0.");
272 Q_ASSERT_X(s >= 0, "QVarLengthArray::QVarLengthArray()", "Size must be greater than or equal to 0.");
273 if (s > Prealloc) {
274 ptr = reinterpret_cast<T *>(malloc(s * sizeof(T)));
275 Q_CHECK_PTR(ptr);
276 a = s;
277 } else {
278 ptr = reinterpret_cast<T *>(array);
279 a = Prealloc;
280 }
281 if (QTypeInfo<T>::isComplex) {
282 T *i = ptr + s;
283 while (i != ptr)
284 new (--i) T;
285 }
286}
287
288template <class T, int Prealloc>
289Q_INLINE_TEMPLATE void QVarLengthArray<T, Prealloc>::resize(int asize)
290{ realloc(asize, qMax(asize, a)); }
291
292template <class T, int Prealloc>
293Q_INLINE_TEMPLATE void QVarLengthArray<T, Prealloc>::reserve(int asize)
294{ if (asize > a) realloc(s, asize); }
295
296template <class T, int Prealloc>
297Q_INLINE_TEMPLATE int QVarLengthArray<T, Prealloc>::indexOf(const T &t, int from) const
298{
299 if (from < 0)
300 from = qMax(from + s, 0);
301 if (from < s) {
302 T *n = ptr + from - 1;
303 T *e = ptr + s;
304 while (++n != e)
305 if (*n == t)
306 return n - ptr;
307 }
308 return -1;
309}
310
311template <class T, int Prealloc>
312Q_INLINE_TEMPLATE int QVarLengthArray<T, Prealloc>::lastIndexOf(const T &t, int from) const
313{
314 if (from < 0)
315 from += s;
316 else if (from >= s)
317 from = s - 1;
318 if (from >= 0) {
319 T *b = ptr;
320 T *n = ptr + from + 1;
321 while (n != b) {
322 if (*--n == t)
323 return n - b;
324 }
325 }
326 return -1;
327}
328
329template <class T, int Prealloc>
330Q_INLINE_TEMPLATE bool QVarLengthArray<T, Prealloc>::contains(const T &t) const
331{
332 T *b = ptr;
333 T *i = ptr + s;
334 while (i != b) {
335 if (*--i == t)
336 return true;
337 }
338 return false;
339}
340
341template <class T, int Prealloc>
342Q_OUTOFLINE_TEMPLATE void QVarLengthArray<T, Prealloc>::append(const T *abuf, int increment)
343{
344 Q_ASSERT(abuf);
345 if (increment <= 0)
346 return;
347
348 const int asize = s + increment;
349
350 if (asize >= a)
351 realloc(s, qMax(s*2, asize));
352
353 if (QTypeInfo<T>::isComplex) {
354 // call constructor for new objects (which can throw)
355 while (s < asize)
356 new (ptr+(s++)) T(*abuf++);
357 } else {
358 memcpy(static_cast<void *>(&ptr[s]), static_cast<const void *>(abuf), increment * sizeof(T));
359 s = asize;
360 }
361}
362
363template <class T, int Prealloc>
364Q_INLINE_TEMPLATE void QVarLengthArray<T, Prealloc>::squeeze()
365{ realloc(s, s); }
366
367template <class T, int Prealloc>
368Q_OUTOFLINE_TEMPLATE void QVarLengthArray<T, Prealloc>::realloc(int asize, int aalloc)
369{
370 Q_ASSERT(aalloc >= asize);
371 T *oldPtr = ptr;
372 int osize = s;
373
374 const int copySize = qMin(asize, osize);
375 Q_ASSUME(copySize >= 0);
376 if (aalloc != a) {
377 if (aalloc > Prealloc) {
378 T* newPtr = reinterpret_cast<T *>(malloc(aalloc * sizeof(T)));
379 Q_CHECK_PTR(newPtr); // could throw
380 // by design: in case of QT_NO_EXCEPTIONS malloc must not fail or it crashes here
381 ptr = newPtr;
382 a = aalloc;
383 } else {
384 ptr = reinterpret_cast<T *>(array);
385 a = Prealloc;
386 }
387 s = 0;
388 if (!QTypeInfoQuery<T>::isRelocatable) {
389 QT_TRY {
390 // move all the old elements
391 while (s < copySize) {
392 new (ptr+s) T(std::move(*(oldPtr+s)));
393 (oldPtr+s)->~T();
394 s++;
395 }
396 } QT_CATCH(...) {
397 // clean up all the old objects and then free the old ptr
398 int sClean = s;
399 while (sClean < osize)
400 (oldPtr+(sClean++))->~T();
401 if (oldPtr != reinterpret_cast<T *>(array) && oldPtr != ptr)
402 free(oldPtr);
403 QT_RETHROW;
404 }
405 } else {
406 memcpy(static_cast<void *>(ptr), static_cast<const void *>(oldPtr), copySize * sizeof(T));
407 }
408 }
409 s = copySize;
410
411 if (QTypeInfo<T>::isComplex) {
412 // destroy remaining old objects
413 while (osize > asize)
414 (oldPtr+(--osize))->~T();
415 }
416
417 if (oldPtr != reinterpret_cast<T *>(array) && oldPtr != ptr)
418 free(oldPtr);
419
420 if (QTypeInfo<T>::isComplex) {
421 // call default constructor for new objects (which can throw)
422 while (s < asize)
423 new (ptr+(s++)) T;
424 } else {
425 s = asize;
426 }
427}
428
429template <class T, int Prealloc>
430Q_OUTOFLINE_TEMPLATE T QVarLengthArray<T, Prealloc>::value(int i) const
431{
432 if (uint(i) >= uint(size())) {
433 return T();
434 }
435 return at(i);
436}
437template <class T, int Prealloc>
438Q_OUTOFLINE_TEMPLATE T QVarLengthArray<T, Prealloc>::value(int i, const T &defaultValue) const
439{
440 return (uint(i) >= uint(size())) ? defaultValue : at(i);
441}
442
443template <class T, int Prealloc>
444inline void QVarLengthArray<T, Prealloc>::insert(int i, T &&t)
445{ Q_ASSERT_X(i >= 0 && i <= s, "QVarLengthArray::insert", "index out of range");
446 insert(cbegin() + i, std::move(t)); }
447template <class T, int Prealloc>
448inline void QVarLengthArray<T, Prealloc>::insert(int i, const T &t)
449{ Q_ASSERT_X(i >= 0 && i <= s, "QVarLengthArray::insert", "index out of range");
450 insert(begin() + i, 1, t); }
451template <class T, int Prealloc>
452inline void QVarLengthArray<T, Prealloc>::insert(int i, int n, const T &t)
453{ Q_ASSERT_X(i >= 0 && i <= s, "QVarLengthArray::insert", "index out of range");
454 insert(begin() + i, n, t); }
455template <class T, int Prealloc>
456inline void QVarLengthArray<T, Prealloc>::remove(int i, int n)
457{ Q_ASSERT_X(i >= 0 && n >= 0 && i + n <= s, "QVarLengthArray::remove", "index out of range");
458 erase(begin() + i, begin() + i + n); }
459template <class T, int Prealloc>
460inline void QVarLengthArray<T, Prealloc>::remove(int i)
461{ Q_ASSERT_X(i >= 0 && i < s, "QVarLengthArray::remove", "index out of range");
462 erase(begin() + i, begin() + i + 1); }
463template <class T, int Prealloc>
464inline void QVarLengthArray<T, Prealloc>::prepend(T &&t)
465{ insert(cbegin(), std::move(t)); }
466template <class T, int Prealloc>
467inline void QVarLengthArray<T, Prealloc>::prepend(const T &t)
468{ insert(begin(), 1, t); }
469
470template <class T, int Prealloc>
471inline void QVarLengthArray<T, Prealloc>::replace(int i, const T &t)
472{
473 Q_ASSERT_X(i >= 0 && i < s, "QVarLengthArray::replace", "index out of range");
474 const T copy(t);
475 data()[i] = copy;
476}
477
478template <class T, int Prealloc>
479Q_OUTOFLINE_TEMPLATE typename QVarLengthArray<T, Prealloc>::iterator QVarLengthArray<T, Prealloc>::insert(const_iterator before, T &&t)
480{
481 Q_ASSERT_X(isValidIterator(before), "QVarLengthArray::insert", "The specified const_iterator argument 'before' is invalid");
482
483 int offset = int(before - ptr);
484 reserve(s + 1);
485 if (!QTypeInfo<T>::isRelocatable) {
486 T *b = ptr + offset;
487 T *i = ptr + s;
488 T *j = i + 1;
489 // The new end-element needs to be constructed, the rest must be move assigned
490 if (i != b) {
491 new (--j) T(std::move(*--i));
492 while (i != b)
493 *--j = std::move(*--i);
494 *b = std::move(t);
495 } else {
496 new (b) T(std::move(t));
497 }
498 } else {
499 T *b = ptr + offset;
500 memmove(static_cast<void *>(b + 1), static_cast<const void *>(b), (s - offset) * sizeof(T));
501 new (b) T(std::move(t));
502 }
503 s += 1;
504 return ptr + offset;
505}
506
507template <class T, int Prealloc>
508Q_OUTOFLINE_TEMPLATE typename QVarLengthArray<T, Prealloc>::iterator QVarLengthArray<T, Prealloc>::insert(const_iterator before, size_type n, const T &t)
509{
510 Q_ASSERT_X(isValidIterator(before), "QVarLengthArray::insert", "The specified const_iterator argument 'before' is invalid");
511
512 int offset = int(before - ptr);
513 if (n != 0) {
514 resize(s + n);
515 const T copy(t);
516 if (!QTypeInfoQuery<T>::isRelocatable) {
517 T *b = ptr + offset;
518 T *j = ptr + s;
519 T *i = j - n;
520 while (i != b)
521 *--j = *--i;
522 i = b + n;
523 while (i != b)
524 *--i = copy;
525 } else {
526 T *b = ptr + offset;
527 T *i = b + n;
528 memmove(static_cast<void *>(i), static_cast<const void *>(b), (s - offset - n) * sizeof(T));
529 while (i != b)
530 new (--i) T(copy);
531 }
532 }
533 return ptr + offset;
534}
535
536template <class T, int Prealloc>
537Q_OUTOFLINE_TEMPLATE typename QVarLengthArray<T, Prealloc>::iterator QVarLengthArray<T, Prealloc>::erase(const_iterator abegin, const_iterator aend)
538{
539 Q_ASSERT_X(isValidIterator(abegin), "QVarLengthArray::insert", "The specified const_iterator argument 'abegin' is invalid");
540 Q_ASSERT_X(isValidIterator(aend), "QVarLengthArray::insert", "The specified const_iterator argument 'aend' is invalid");
541
542 int f = int(abegin - ptr);
543 int l = int(aend - ptr);
544 int n = l - f;
545 if (QTypeInfo<T>::isComplex) {
546 std::copy(ptr + l, ptr + s, QT_MAKE_CHECKED_ARRAY_ITERATOR(ptr + f, s - f));
547 T *i = ptr + s;
548 T *b = ptr + s - n;
549 while (i != b) {
550 --i;
551 i->~T();
552 }
553 } else {
554 memmove(static_cast<void *>(ptr + f), static_cast<const void *>(ptr + l), (s - l) * sizeof(T));
555 }
556 s -= n;
557 return ptr + f;
558}
559
560template <typename T, int Prealloc1, int Prealloc2>
561bool operator==(const QVarLengthArray<T, Prealloc1> &l, const QVarLengthArray<T, Prealloc2> &r)
562{
563 if (l.size() != r.size())
564 return false;
565 const T *rb = r.begin();
566 const T *b = l.begin();
567 const T *e = l.end();
568 return std::equal(b, e, QT_MAKE_CHECKED_ARRAY_ITERATOR(rb, r.size()));
569}
570
571template <typename T, int Prealloc1, int Prealloc2>
572bool operator!=(const QVarLengthArray<T, Prealloc1> &l, const QVarLengthArray<T, Prealloc2> &r)
573{
574 return !(l == r);
575}
576
577template <typename T, int Prealloc1, int Prealloc2>
578bool operator<(const QVarLengthArray<T, Prealloc1> &lhs, const QVarLengthArray<T, Prealloc2> &rhs)
579 noexcept(noexcept(std::lexicographical_compare(lhs.begin(), lhs.end(),
580 rhs.begin(), rhs.end())))
581{
582 return std::lexicographical_compare(lhs.begin(), lhs.end(),
583 rhs.begin(), rhs.end());
584}
585
586template <typename T, int Prealloc1, int Prealloc2>
587inline bool operator>(const QVarLengthArray<T, Prealloc1> &lhs, const QVarLengthArray<T, Prealloc2> &rhs)
588 noexcept(noexcept(lhs < rhs))
589{
590 return rhs < lhs;
591}
592
593template <typename T, int Prealloc1, int Prealloc2>
594inline bool operator<=(const QVarLengthArray<T, Prealloc1> &lhs, const QVarLengthArray<T, Prealloc2> &rhs)
595 noexcept(noexcept(lhs < rhs))
596{
597 return !(lhs > rhs);
598}
599
600template <typename T, int Prealloc1, int Prealloc2>
601inline bool operator>=(const QVarLengthArray<T, Prealloc1> &lhs, const QVarLengthArray<T, Prealloc2> &rhs)
602 noexcept(noexcept(lhs < rhs))
603{
604 return !(lhs < rhs);
605}
606
607template <typename T, int Prealloc>
608uint qHash(const QVarLengthArray<T, Prealloc> &key, uint seed = 0)
609 noexcept(noexcept(qHashRange(key.cbegin(), key.cend(), seed)))
610{
611 return qHashRange(key.cbegin(), key.cend(), seed);
612}
613
614QT_END_NAMESPACE
615
616#endif // QVARLENGTHARRAY_H
617