michael@0: /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ michael@0: /* vim: set ts=8 sts=2 et sw=2 tw=80: */ michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: /* EnumeratedArray is like Array, but indexed by a typed enum. */ michael@0: michael@0: #ifndef mozilla_EnumeratedArray_h michael@0: #define mozilla_EnumeratedArray_h michael@0: michael@0: #include "mozilla/Array.h" michael@0: #include "mozilla/TypedEnum.h" michael@0: michael@0: namespace mozilla { michael@0: michael@0: /** michael@0: * EnumeratedArray is a fixed-size array container for use when an michael@0: * array is indexed by a specific enum class, as currently implemented michael@0: * by MOZ_BEGIN_ENUM_CLASS. michael@0: * michael@0: * This provides type safety by guarding at compile time against accidentally michael@0: * indexing such arrays with unrelated values. This also removes the need michael@0: * for manual casting when using a typed enum value to index arrays. michael@0: * michael@0: * Aside from the typing of indices, EnumeratedArray is similar to Array. michael@0: * michael@0: * Example: michael@0: * michael@0: * MOZ_BEGIN_ENUM_CLASS(AnimalSpecies) michael@0: * Cow, michael@0: * Sheep, michael@0: * Count michael@0: * MOZ_END_ENUM_CLASS(AnimalSpecies) michael@0: * michael@0: * EnumeratedArray headCount; michael@0: * michael@0: * headCount[AnimalSpecies::Cow] = 17; michael@0: * headCount[AnimalSpecies::Sheep] = 30; michael@0: * michael@0: */ michael@0: template michael@0: class EnumeratedArray michael@0: { michael@0: public: michael@0: static const size_t Size = size_t(SizeAsEnumValue); michael@0: michael@0: private: michael@0: Array mArray; michael@0: michael@0: public: michael@0: EnumeratedArray() {} michael@0: michael@0: explicit EnumeratedArray(const EnumeratedArray& aOther) michael@0: { michael@0: for (size_t i = 0; i < Size; i++) michael@0: mArray[i] = aOther.mArray[i]; michael@0: } michael@0: michael@0: explicit EnumeratedArray(const ValueType (&aOther)[Size]) michael@0: { michael@0: for (size_t i = 0; i < Size; i++) michael@0: mArray[i] = aOther[i]; michael@0: } michael@0: michael@0: ValueType& operator[](IndexType aIndex) michael@0: { michael@0: return mArray[size_t(aIndex)]; michael@0: } michael@0: michael@0: const ValueType& operator[](IndexType aIndex) const michael@0: { michael@0: return mArray[size_t(aIndex)]; michael@0: } michael@0: }; michael@0: michael@0: } // namespace mozilla michael@0: michael@0: #endif // mozilla_EnumeratedArray_h