• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2011 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #ifndef SkTArray_DEFINED
9 #define SkTArray_DEFINED
10 
11 #include "../private/SkSafe32.h"
12 #include "../private/SkTLogic.h"
13 #include "../private/SkTemplates.h"
14 #include "SkTypes.h"
15 
16 #include <new>
17 #include <utility>
18 
19 /** When MEM_MOVE is true T will be bit copied when moved.
20     When MEM_MOVE is false, T will be copy constructed / destructed.
21     In all cases T will be default-initialized on allocation,
22     and its destructor will be called from this object's destructor.
23 */
24 template <typename T, bool MEM_MOVE = false> class SkTArray {
25 public:
26     /**
27      * Creates an empty array with no initial storage
28      */
SkTArray()29     SkTArray() { this->init(); }
30 
31     /**
32      * Creates an empty array that will preallocate space for reserveCount
33      * elements.
34      */
SkTArray(int reserveCount)35     explicit SkTArray(int reserveCount) { this->init(0, reserveCount); }
36 
37     /**
38      * Copies one array to another. The new array will be heap allocated.
39      */
SkTArray(const SkTArray & that)40     SkTArray(const SkTArray& that) {
41         this->init(that.fCount);
42         this->copy(that.fItemArray);
43     }
44 
SkTArray(SkTArray && that)45     SkTArray(SkTArray&& that) {
46         // TODO: If 'that' owns its memory why don't we just steal the pointer?
47         this->init(that.fCount);
48         that.move(fMemArray);
49         that.fCount = 0;
50     }
51 
52     /**
53      * Creates a SkTArray by copying contents of a standard C array. The new
54      * array will be heap allocated. Be careful not to use this constructor
55      * when you really want the (void*, int) version.
56      */
SkTArray(const T * array,int count)57     SkTArray(const T* array, int count) {
58         this->init(count);
59         this->copy(array);
60     }
61 
62     SkTArray& operator=(const SkTArray& that) {
63         if (this == &that) {
64             return *this;
65         }
66         for (int i = 0; i < fCount; ++i) {
67             fItemArray[i].~T();
68         }
69         fCount = 0;
70         this->checkRealloc(that.count());
71         fCount = that.count();
72         this->copy(that.fItemArray);
73         return *this;
74     }
75     SkTArray& operator=(SkTArray&& that) {
76         if (this == &that) {
77             return *this;
78         }
79         for (int i = 0; i < fCount; ++i) {
80             fItemArray[i].~T();
81         }
82         fCount = 0;
83         this->checkRealloc(that.count());
84         fCount = that.count();
85         that.move(fMemArray);
86         that.fCount = 0;
87         return *this;
88     }
89 
~SkTArray()90     ~SkTArray() {
91         for (int i = 0; i < fCount; ++i) {
92             fItemArray[i].~T();
93         }
94         if (fOwnMemory) {
95             sk_free(fMemArray);
96         }
97     }
98 
99     /**
100      * Resets to count() == 0 and resets any reserve count.
101      */
reset()102     void reset() {
103         this->pop_back_n(fCount);
104         fReserved = false;
105     }
106 
107     /**
108      * Resets to count() = n newly constructed T objects and resets any reserve count.
109      */
reset(int n)110     void reset(int n) {
111         SkASSERT(n >= 0);
112         for (int i = 0; i < fCount; ++i) {
113             fItemArray[i].~T();
114         }
115         // Set fCount to 0 before calling checkRealloc so that no elements are moved.
116         fCount = 0;
117         this->checkRealloc(n);
118         fCount = n;
119         for (int i = 0; i < fCount; ++i) {
120             new (fItemArray + i) T;
121         }
122         fReserved = false;
123     }
124 
125     /**
126      * Resets to a copy of a C array and resets any reserve count.
127      */
reset(const T * array,int count)128     void reset(const T* array, int count) {
129         for (int i = 0; i < fCount; ++i) {
130             fItemArray[i].~T();
131         }
132         fCount = 0;
133         this->checkRealloc(count);
134         fCount = count;
135         this->copy(array);
136         fReserved = false;
137     }
138 
139     /**
140      * Ensures there is enough reserved space for n additional elements. The is guaranteed at least
141      * until the array size grows above n and subsequently shrinks below n, any version of reset()
142      * is called, or reserve() is called again.
143      */
reserve(int n)144     void reserve(int n) {
145         SkASSERT(n >= 0);
146         if (n > 0) {
147             this->checkRealloc(n);
148             fReserved = fOwnMemory;
149         } else {
150             fReserved = false;
151         }
152     }
153 
removeShuffle(int n)154     void removeShuffle(int n) {
155         SkASSERT(n < fCount);
156         int newCount = fCount - 1;
157         fCount = newCount;
158         fItemArray[n].~T();
159         if (n != newCount) {
160             this->move(n, newCount);
161         }
162     }
163 
164     /**
165      * Number of elements in the array.
166      */
count()167     int count() const { return fCount; }
168 
169     /**
170      * Is the array empty.
171      */
empty()172     bool empty() const { return !fCount; }
173 
174     /**
175      * Adds 1 new default-initialized T value and returns it by reference. Note
176      * the reference only remains valid until the next call that adds or removes
177      * elements.
178      */
push_back()179     T& push_back() {
180         void* newT = this->push_back_raw(1);
181         return *new (newT) T;
182     }
183 
184     /**
185      * Version of above that uses a copy constructor to initialize the new item
186      */
push_back(const T & t)187     T& push_back(const T& t) {
188         void* newT = this->push_back_raw(1);
189         return *new (newT) T(t);
190     }
191 
192     /**
193      * Version of above that uses a move constructor to initialize the new item
194      */
push_back(T && t)195     T& push_back(T&& t) {
196         void* newT = this->push_back_raw(1);
197         return *new (newT) T(std::move(t));
198     }
199 
200     /**
201      *  Construct a new T at the back of this array.
202      */
emplace_back(Args &&...args)203     template<class... Args> T& emplace_back(Args&&... args) {
204         void* newT = this->push_back_raw(1);
205         return *new (newT) T(std::forward<Args>(args)...);
206     }
207 
208     /**
209      * Allocates n more default-initialized T values, and returns the address of
210      * the start of that new range. Note: this address is only valid until the
211      * next API call made on the array that might add or remove elements.
212      */
push_back_n(int n)213     T* push_back_n(int n) {
214         SkASSERT(n >= 0);
215         void* newTs = this->push_back_raw(n);
216         for (int i = 0; i < n; ++i) {
217             new (static_cast<char*>(newTs) + i * sizeof(T)) T;
218         }
219         return static_cast<T*>(newTs);
220     }
221 
222     /**
223      * Version of above that uses a copy constructor to initialize all n items
224      * to the same T.
225      */
push_back_n(int n,const T & t)226     T* push_back_n(int n, const T& t) {
227         SkASSERT(n >= 0);
228         void* newTs = this->push_back_raw(n);
229         for (int i = 0; i < n; ++i) {
230             new (static_cast<char*>(newTs) + i * sizeof(T)) T(t);
231         }
232         return static_cast<T*>(newTs);
233     }
234 
235     /**
236      * Version of above that uses a copy constructor to initialize the n items
237      * to separate T values.
238      */
push_back_n(int n,const T t[])239     T* push_back_n(int n, const T t[]) {
240         SkASSERT(n >= 0);
241         this->checkRealloc(n);
242         for (int i = 0; i < n; ++i) {
243             new (fItemArray + fCount + i) T(t[i]);
244         }
245         fCount += n;
246         return fItemArray + fCount - n;
247     }
248 
249     /**
250      * Version of above that uses the move constructor to set n items.
251      */
move_back_n(int n,T * t)252     T* move_back_n(int n, T* t) {
253         SkASSERT(n >= 0);
254         this->checkRealloc(n);
255         for (int i = 0; i < n; ++i) {
256             new (fItemArray + fCount + i) T(std::move(t[i]));
257         }
258         fCount += n;
259         return fItemArray + fCount - n;
260     }
261 
262     /**
263      * Removes the last element. Not safe to call when count() == 0.
264      */
pop_back()265     void pop_back() {
266         SkASSERT(fCount > 0);
267         --fCount;
268         fItemArray[fCount].~T();
269         this->checkRealloc(0);
270     }
271 
272     /**
273      * Removes the last n elements. Not safe to call when count() < n.
274      */
pop_back_n(int n)275     void pop_back_n(int n) {
276         SkASSERT(n >= 0);
277         SkASSERT(fCount >= n);
278         fCount -= n;
279         for (int i = 0; i < n; ++i) {
280             fItemArray[fCount + i].~T();
281         }
282         this->checkRealloc(0);
283     }
284 
285     /**
286      * Pushes or pops from the back to resize. Pushes will be default
287      * initialized.
288      */
resize_back(int newCount)289     void resize_back(int newCount) {
290         SkASSERT(newCount >= 0);
291 
292         if (newCount > fCount) {
293             this->push_back_n(newCount - fCount);
294         } else if (newCount < fCount) {
295             this->pop_back_n(fCount - newCount);
296         }
297     }
298 
299     /** Swaps the contents of this array with that array. Does a pointer swap if possible,
300         otherwise copies the T values. */
swap(SkTArray & that)301     void swap(SkTArray& that) {
302         using std::swap;
303         if (this == &that) {
304             return;
305         }
306         if (fOwnMemory && that.fOwnMemory) {
307             swap(fItemArray, that.fItemArray);
308             swap(fCount, that.fCount);
309             swap(fAllocCount, that.fAllocCount);
310         } else {
311             // This could be more optimal...
312             SkTArray copy(std::move(that));
313             that = std::move(*this);
314             *this = std::move(copy);
315         }
316     }
317 
begin()318     T* begin() {
319         return fItemArray;
320     }
begin()321     const T* begin() const {
322         return fItemArray;
323     }
end()324     T* end() {
325         return fItemArray ? fItemArray + fCount : nullptr;
326     }
end()327     const T* end() const {
328         return fItemArray ? fItemArray + fCount : nullptr;
329     }
data()330     T* data() { return fItemArray; }
data()331     const T* data() const { return fItemArray; }
size()332     size_t size() const { return (size_t)fCount; }
resize(size_t count)333     void resize(size_t count) { this->resize_back((int)count); }
334 
335    /**
336      * Get the i^th element.
337      */
338     T& operator[] (int i) {
339         SkASSERT(i < fCount);
340         SkASSERT(i >= 0);
341         return fItemArray[i];
342     }
343 
344     const T& operator[] (int i) const {
345         SkASSERT(i < fCount);
346         SkASSERT(i >= 0);
347         return fItemArray[i];
348     }
349 
350     /**
351      * equivalent to operator[](0)
352      */
front()353     T& front() { SkASSERT(fCount > 0); return fItemArray[0];}
354 
front()355     const T& front() const { SkASSERT(fCount > 0); return fItemArray[0];}
356 
357     /**
358      * equivalent to operator[](count() - 1)
359      */
back()360     T& back() { SkASSERT(fCount); return fItemArray[fCount - 1];}
361 
back()362     const T& back() const { SkASSERT(fCount > 0); return fItemArray[fCount - 1];}
363 
364     /**
365      * equivalent to operator[](count()-1-i)
366      */
fromBack(int i)367     T& fromBack(int i) {
368         SkASSERT(i >= 0);
369         SkASSERT(i < fCount);
370         return fItemArray[fCount - i - 1];
371     }
372 
fromBack(int i)373     const T& fromBack(int i) const {
374         SkASSERT(i >= 0);
375         SkASSERT(i < fCount);
376         return fItemArray[fCount - i - 1];
377     }
378 
379     bool operator==(const SkTArray<T, MEM_MOVE>& right) const {
380         int leftCount = this->count();
381         if (leftCount != right.count()) {
382             return false;
383         }
384         for (int index = 0; index < leftCount; ++index) {
385             if (fItemArray[index] != right.fItemArray[index]) {
386                 return false;
387             }
388         }
389         return true;
390     }
391 
392     bool operator!=(const SkTArray<T, MEM_MOVE>& right) const {
393         return !(*this == right);
394     }
395 
396     inline int allocCntForTest() const;
397 
398 protected:
399     /**
400      * Creates an empty array that will use the passed storage block until it
401      * is insufficiently large to hold the entire array.
402      */
403     template <int N>
SkTArray(SkAlignedSTStorage<N,T> * storage)404     SkTArray(SkAlignedSTStorage<N,T>* storage) {
405         this->initWithPreallocatedStorage(0, storage->get(), N);
406     }
407 
408     /**
409      * Copy another array, using preallocated storage if preAllocCount >=
410      * array.count(). Otherwise storage will only be used when array shrinks
411      * to fit.
412      */
413     template <int N>
SkTArray(const SkTArray & array,SkAlignedSTStorage<N,T> * storage)414     SkTArray(const SkTArray& array, SkAlignedSTStorage<N,T>* storage) {
415         this->initWithPreallocatedStorage(array.fCount, storage->get(), N);
416         this->copy(array.fItemArray);
417     }
418 
419     /**
420      * Move another array, using preallocated storage if preAllocCount >=
421      * array.count(). Otherwise storage will only be used when array shrinks
422      * to fit.
423      */
424     template <int N>
SkTArray(SkTArray && array,SkAlignedSTStorage<N,T> * storage)425     SkTArray(SkTArray&& array, SkAlignedSTStorage<N,T>* storage) {
426         this->initWithPreallocatedStorage(array.fCount, storage->get(), N);
427         array.move(fMemArray);
428         array.fCount = 0;
429     }
430 
431     /**
432      * Copy a C array, using preallocated storage if preAllocCount >=
433      * count. Otherwise storage will only be used when array shrinks
434      * to fit.
435      */
436     template <int N>
SkTArray(const T * array,int count,SkAlignedSTStorage<N,T> * storage)437     SkTArray(const T* array, int count, SkAlignedSTStorage<N,T>* storage) {
438         this->initWithPreallocatedStorage(count, storage->get(), N);
439         this->copy(array);
440     }
441 
442 private:
443     void init(int count = 0, int reserveCount = 0) {
444         SkASSERT(count >= 0);
445         SkASSERT(reserveCount >= 0);
446         fCount = count;
447         if (!count && !reserveCount) {
448             fAllocCount = 0;
449             fMemArray = nullptr;
450             fOwnMemory = true;
451             fReserved = false;
452         } else {
453             fAllocCount = SkTMax(count, SkTMax(kMinHeapAllocCount, reserveCount));
454             fMemArray = sk_malloc_throw(fAllocCount, sizeof(T));
455             fOwnMemory = true;
456             fReserved = reserveCount > 0;
457         }
458     }
459 
initWithPreallocatedStorage(int count,void * preallocStorage,int preallocCount)460     void initWithPreallocatedStorage(int count, void* preallocStorage, int preallocCount) {
461         SkASSERT(count >= 0);
462         SkASSERT(preallocCount > 0);
463         SkASSERT(preallocStorage);
464         fCount = count;
465         fMemArray = nullptr;
466         fReserved = false;
467         if (count > preallocCount) {
468             fAllocCount = SkTMax(count, kMinHeapAllocCount);
469             fMemArray = sk_malloc_throw(fAllocCount, sizeof(T));
470             fOwnMemory = true;
471         } else {
472             fAllocCount = preallocCount;
473             fMemArray = preallocStorage;
474             fOwnMemory = false;
475         }
476     }
477 
478     /** In the following move and copy methods, 'dst' is assumed to be uninitialized raw storage.
479      *  In the following move methods, 'src' is destroyed leaving behind uninitialized raw storage.
480      */
copy(const T * src)481     void copy(const T* src) {
482         // Some types may be trivially copyable, in which case we *could* use memcopy; but
483         // MEM_MOVE == true implies that the type is trivially movable, and not necessarily
484         // trivially copyable (think sk_sp<>).  So short of adding another template arg, we
485         // must be conservative and use copy construction.
486         for (int i = 0; i < fCount; ++i) {
487             new (fItemArray + i) T(src[i]);
488         }
489     }
490 
SK_WHEN(E,void)491     template <bool E = MEM_MOVE> SK_WHEN(E, void) move(int dst, int src) {
492         memcpy(&fItemArray[dst], &fItemArray[src], sizeof(T));
493     }
SK_WHEN(E,void)494     template <bool E = MEM_MOVE> SK_WHEN(E, void) move(void* dst) {
495         sk_careful_memcpy(dst, fMemArray, fCount * sizeof(T));
496     }
497 
move(int dst,int src)498     template <bool E = MEM_MOVE> SK_WHEN(!E, void) move(int dst, int src) {
499         new (&fItemArray[dst]) T(std::move(fItemArray[src]));
500         fItemArray[src].~T();
501     }
move(void * dst)502     template <bool E = MEM_MOVE> SK_WHEN(!E, void) move(void* dst) {
503         for (int i = 0; i < fCount; ++i) {
504             new (static_cast<char*>(dst) + sizeof(T) * i) T(std::move(fItemArray[i]));
505             fItemArray[i].~T();
506         }
507     }
508 
509     static constexpr int kMinHeapAllocCount = 8;
510 
511     // Helper function that makes space for n objects, adjusts the count, but does not initialize
512     // the new objects.
push_back_raw(int n)513     void* push_back_raw(int n) {
514         this->checkRealloc(n);
515         void* ptr = fItemArray + fCount;
516         fCount += n;
517         return ptr;
518     }
519 
checkRealloc(int delta)520     void checkRealloc(int delta) {
521         SkASSERT(fCount >= 0);
522         SkASSERT(fAllocCount >= 0);
523         SkASSERT(-delta <= fCount);
524 
525         // Move into 64bit math temporarily, to avoid local overflows
526         int64_t newCount = fCount + delta;
527 
528         // We allow fAllocCount to be in the range [newCount, 3*newCount]. We also never shrink
529         // when we're currently using preallocated memory, would allocate less than
530         // kMinHeapAllocCount, or a reserve count was specified that has yet to be exceeded.
531         bool mustGrow = newCount > fAllocCount;
532         bool shouldShrink = fAllocCount > 3 * newCount && fOwnMemory && !fReserved;
533         if (!mustGrow && !shouldShrink) {
534             return;
535         }
536 
537 
538         // Whether we're growing or shrinking, we leave at least 50% extra space for future growth.
539         int64_t newAllocCount = newCount + ((newCount + 1) >> 1);
540         // Align the new allocation count to kMinHeapAllocCount.
541         static_assert(SkIsPow2(kMinHeapAllocCount), "min alloc count not power of two.");
542         newAllocCount = (newAllocCount + (kMinHeapAllocCount - 1)) & ~(kMinHeapAllocCount - 1);
543         // At small sizes the old and new alloc count can both be kMinHeapAllocCount.
544         if (newAllocCount == fAllocCount) {
545             return;
546         }
547 
548         fAllocCount = Sk64_pin_to_s32(newAllocCount);
549         SkASSERT(fAllocCount >= newCount);
550         void* newMemArray = sk_malloc_throw(fAllocCount, sizeof(T));
551         this->move(newMemArray);
552         if (fOwnMemory) {
553             sk_free(fMemArray);
554 
555         }
556         fMemArray = newMemArray;
557         fOwnMemory = true;
558         fReserved = false;
559     }
560 
561     union {
562         T*       fItemArray;
563         void*    fMemArray;
564     };
565     int fCount;
566     int fAllocCount;
567     bool fOwnMemory : 1;
568     bool fReserved : 1;
569 };
570 
swap(SkTArray<T,M> & a,SkTArray<T,M> & b)571 template <typename T, bool M> static inline void swap(SkTArray<T, M>& a, SkTArray<T, M>& b) {
572     a.swap(b);
573 }
574 
575 template<typename T, bool MEM_MOVE> constexpr int SkTArray<T, MEM_MOVE>::kMinHeapAllocCount;
576 
577 /**
578  * Subclass of SkTArray that contains a preallocated memory block for the array.
579  */
580 template <int N, typename T, bool MEM_MOVE= false>
581 class SkSTArray : public SkTArray<T, MEM_MOVE> {
582 private:
583     typedef SkTArray<T, MEM_MOVE> INHERITED;
584 
585 public:
SkSTArray()586     SkSTArray() : INHERITED(&fStorage) {
587     }
588 
SkSTArray(const SkSTArray & array)589     SkSTArray(const SkSTArray& array)
590         : INHERITED(array, &fStorage) {
591     }
592 
SkSTArray(SkSTArray && array)593     SkSTArray(SkSTArray&& array)
594         : INHERITED(std::move(array), &fStorage) {
595     }
596 
SkSTArray(const INHERITED & array)597     explicit SkSTArray(const INHERITED& array)
598         : INHERITED(array, &fStorage) {
599     }
600 
SkSTArray(INHERITED && array)601     explicit SkSTArray(INHERITED&& array)
602         : INHERITED(std::move(array), &fStorage) {
603     }
604 
SkSTArray(int reserveCount)605     explicit SkSTArray(int reserveCount)
606         : INHERITED(reserveCount) {
607     }
608 
SkSTArray(const T * array,int count)609     SkSTArray(const T* array, int count)
610         : INHERITED(array, count, &fStorage) {
611     }
612 
613     SkSTArray& operator=(const SkSTArray& array) {
614         INHERITED::operator=(array);
615         return *this;
616     }
617 
618     SkSTArray& operator=(SkSTArray&& array) {
619         INHERITED::operator=(std::move(array));
620         return *this;
621     }
622 
623     SkSTArray& operator=(const INHERITED& array) {
624         INHERITED::operator=(array);
625         return *this;
626     }
627 
628     SkSTArray& operator=(INHERITED&& array) {
629         INHERITED::operator=(std::move(array));
630         return *this;
631     }
632 
633 private:
634     SkAlignedSTStorage<N,T> fStorage;
635 };
636 
637 #endif
638