RangedArray.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. * A compile-time constant-length array, with bounds-checking assertions -- but
  8. * unlike mozilla::Array, with indexes biased by a constant.
  9. *
  10. * Thus where mozilla::Array<int, 3> is a three-element array indexed by [0, 3),
  11. * mozilla::RangedArray<int, 8, 3> is a three-element array indexed by [8, 11).
  12. */
  13. #ifndef mozilla_RangedArray_h
  14. #define mozilla_RangedArray_h
  15. #include "mozilla/Array.h"
  16. namespace mozilla {
  17. template<typename T, size_t MinIndex, size_t Length>
  18. class RangedArray
  19. {
  20. private:
  21. typedef Array<T, Length> ArrayType;
  22. ArrayType mArr;
  23. public:
  24. T& operator[](size_t aIndex)
  25. {
  26. MOZ_ASSERT(aIndex == MinIndex || aIndex > MinIndex);
  27. return mArr[aIndex - MinIndex];
  28. }
  29. const T& operator[](size_t aIndex) const
  30. {
  31. MOZ_ASSERT(aIndex == MinIndex || aIndex > MinIndex);
  32. return mArr[aIndex - MinIndex];
  33. }
  34. typedef typename ArrayType::iterator iterator;
  35. typedef typename ArrayType::const_iterator const_iterator;
  36. typedef typename ArrayType::reverse_iterator reverse_iterator;
  37. typedef typename ArrayType::const_reverse_iterator const_reverse_iterator;
  38. // Methods for range-based for loops.
  39. iterator begin() { return mArr.begin(); }
  40. const_iterator begin() const { return mArr.begin(); }
  41. const_iterator cbegin() const { return mArr.cbegin(); }
  42. iterator end() { return mArr.end(); }
  43. const_iterator end() const { return mArr.end(); }
  44. const_iterator cend() const { return mArr.cend(); }
  45. // Methods for reverse iterating.
  46. reverse_iterator rbegin() { return mArr.rbegin(); }
  47. const_reverse_iterator rbegin() const { return mArr.rbegin(); }
  48. const_reverse_iterator crbegin() const { return mArr.crbegin(); }
  49. reverse_iterator rend() { return mArr.rend(); }
  50. const_reverse_iterator rend() const { return mArr.rend(); }
  51. const_reverse_iterator crend() const { return mArr.crend(); }
  52. };
  53. } // namespace mozilla
  54. #endif // mozilla_RangedArray_h