|
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 /* EnumeratedArray is like Array, but indexed by a typed enum. */ |
|
8 |
|
9 #ifndef mozilla_EnumeratedArray_h |
|
10 #define mozilla_EnumeratedArray_h |
|
11 |
|
12 #include "mozilla/Array.h" |
|
13 #include "mozilla/TypedEnum.h" |
|
14 |
|
15 namespace mozilla { |
|
16 |
|
17 /** |
|
18 * EnumeratedArray is a fixed-size array container for use when an |
|
19 * array is indexed by a specific enum class, as currently implemented |
|
20 * by MOZ_BEGIN_ENUM_CLASS. |
|
21 * |
|
22 * This provides type safety by guarding at compile time against accidentally |
|
23 * indexing such arrays with unrelated values. This also removes the need |
|
24 * for manual casting when using a typed enum value to index arrays. |
|
25 * |
|
26 * Aside from the typing of indices, EnumeratedArray is similar to Array. |
|
27 * |
|
28 * Example: |
|
29 * |
|
30 * MOZ_BEGIN_ENUM_CLASS(AnimalSpecies) |
|
31 * Cow, |
|
32 * Sheep, |
|
33 * Count |
|
34 * MOZ_END_ENUM_CLASS(AnimalSpecies) |
|
35 * |
|
36 * EnumeratedArray<AnimalSpecies, AnimalSpecies::Count, int> headCount; |
|
37 * |
|
38 * headCount[AnimalSpecies::Cow] = 17; |
|
39 * headCount[AnimalSpecies::Sheep] = 30; |
|
40 * |
|
41 */ |
|
42 template<typename IndexType, |
|
43 MOZ_TEMPLATE_ENUM_CLASS_ENUM_TYPE(IndexType) SizeAsEnumValue, |
|
44 typename ValueType> |
|
45 class EnumeratedArray |
|
46 { |
|
47 public: |
|
48 static const size_t Size = size_t(SizeAsEnumValue); |
|
49 |
|
50 private: |
|
51 Array<ValueType, Size> mArray; |
|
52 |
|
53 public: |
|
54 EnumeratedArray() {} |
|
55 |
|
56 explicit EnumeratedArray(const EnumeratedArray& aOther) |
|
57 { |
|
58 for (size_t i = 0; i < Size; i++) |
|
59 mArray[i] = aOther.mArray[i]; |
|
60 } |
|
61 |
|
62 explicit EnumeratedArray(const ValueType (&aOther)[Size]) |
|
63 { |
|
64 for (size_t i = 0; i < Size; i++) |
|
65 mArray[i] = aOther[i]; |
|
66 } |
|
67 |
|
68 ValueType& operator[](IndexType aIndex) |
|
69 { |
|
70 return mArray[size_t(aIndex)]; |
|
71 } |
|
72 |
|
73 const ValueType& operator[](IndexType aIndex) const |
|
74 { |
|
75 return mArray[size_t(aIndex)]; |
|
76 } |
|
77 }; |
|
78 |
|
79 } // namespace mozilla |
|
80 |
|
81 #endif // mozilla_EnumeratedArray_h |