Fix typo in 9b54bd30006c008b4a951331b273613d5bac3abf
[pm.git] / mfbt / EnumeratedArray.h
blobd6d7bad613eb67b5e4908d14279ace48df1ca90d
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/. */
7 /* EnumeratedArray is like Array, but indexed by a typed enum. */
9 #ifndef mozilla_EnumeratedArray_h
10 #define mozilla_EnumeratedArray_h
12 #include "mozilla/Array.h"
14 namespace mozilla {
16 /**
17 * EnumeratedArray is a fixed-size array container for use when an
18 * array is indexed by a specific enum class.
20 * This provides type safety by guarding at compile time against accidentally
21 * indexing such arrays with unrelated values. This also removes the need
22 * for manual casting when using a typed enum value to index arrays.
24 * Aside from the typing of indices, EnumeratedArray is similar to Array.
26 * Example:
28 * enum class AnimalSpecies {
29 * Cow,
30 * Sheep,
31 * Count
32 * };
34 * EnumeratedArray<AnimalSpecies, AnimalSpecies::Count, int> headCount;
36 * headCount[AnimalSpecies::Cow] = 17;
37 * headCount[AnimalSpecies::Sheep] = 30;
40 template<typename IndexType,
41 IndexType SizeAsEnumValue,
42 typename ValueType>
43 class EnumeratedArray
45 public:
46 static const size_t kSize = size_t(SizeAsEnumValue);
48 private:
49 Array<ValueType, kSize> mArray;
51 public:
52 EnumeratedArray() {}
54 explicit EnumeratedArray(const EnumeratedArray& aOther)
56 for (size_t i = 0; i < kSize; i++) {
57 mArray[i] = aOther.mArray[i];
61 ValueType& operator[](IndexType aIndex)
63 return mArray[size_t(aIndex)];
66 const ValueType& operator[](IndexType aIndex) const
68 return mArray[size_t(aIndex)];
72 } // namespace mozilla
74 #endif // mozilla_EnumeratedArray_h