nsStyleAutoArray.h (2492B)
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */ 3 /* This Source Code Form is subject to the terms of the Mozilla Public 4 * License, v. 2.0. If a copy of the MPL was not distributed with this 5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 6 7 #ifndef nsStyleAutoArray_h_ 8 #define nsStyleAutoArray_h_ 9 10 #include "mozilla/Assertions.h" 11 #include "nsTArray.h" 12 13 /** 14 * An array of objects, similar to AutoTArray<T,1> but which is memmovable. It 15 * always has length >= 1. 16 */ 17 template <typename T> 18 class nsStyleAutoArray { 19 public: 20 // This constructor places a single element in mFirstElement. 21 enum WithSingleInitialElement { WITH_SINGLE_INITIAL_ELEMENT }; 22 explicit nsStyleAutoArray(WithSingleInitialElement) {} 23 24 nsStyleAutoArray(const nsStyleAutoArray&) = delete; 25 nsStyleAutoArray& operator=(const nsStyleAutoArray&) = delete; 26 27 nsStyleAutoArray(nsStyleAutoArray&&) = default; 28 nsStyleAutoArray& operator=(nsStyleAutoArray&&) = default; 29 30 bool Assign(const nsStyleAutoArray& aOther, mozilla::fallible_t) { 31 mFirstElement = aOther.mFirstElement; 32 return mOtherElements.Assign(aOther.mOtherElements, mozilla::fallible); 33 } 34 35 nsStyleAutoArray Clone() const { 36 nsStyleAutoArray res(WITH_SINGLE_INITIAL_ELEMENT); 37 res.mFirstElement = mFirstElement; 38 res.mOtherElements = mOtherElements.Clone(); 39 return res; 40 } 41 42 bool operator==(const nsStyleAutoArray& aOther) const { 43 return Length() == aOther.Length() && 44 mFirstElement == aOther.mFirstElement && 45 mOtherElements == aOther.mOtherElements; 46 } 47 bool operator!=(const nsStyleAutoArray&) const = default; 48 49 size_t Length() const { return mOtherElements.Length() + 1; } 50 const T& operator[](size_t aIndex) const { 51 return aIndex == 0 ? mFirstElement : mOtherElements[aIndex - 1]; 52 } 53 T& operator[](size_t aIndex) { 54 return aIndex == 0 ? mFirstElement : mOtherElements[aIndex - 1]; 55 } 56 57 void EnsureLengthAtLeast(size_t aMinLen) { 58 if (aMinLen > 0) { 59 mOtherElements.EnsureLengthAtLeast(aMinLen - 1); 60 } 61 } 62 63 void SetLengthNonZero(size_t aNewLen) { 64 MOZ_ASSERT(aNewLen > 0); 65 mOtherElements.SetLength(aNewLen - 1); 66 } 67 68 void TruncateLengthNonZero(size_t aNewLen) { 69 MOZ_ASSERT(aNewLen > 0); 70 MOZ_ASSERT(aNewLen <= Length()); 71 mOtherElements.TruncateLength(aNewLen - 1); 72 } 73 74 private: 75 T mFirstElement; 76 nsTArray<T> mOtherElements; 77 }; 78 79 #endif /* nsStyleAutoArray_h_ */