Array.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. /* A compile-time constant-length array with bounds-checking assertions. */
  7. #ifndef mozilla_Array_h
  8. #define mozilla_Array_h
  9. #include "mozilla/Assertions.h"
  10. #include "mozilla/Attributes.h"
  11. #include "mozilla/Move.h"
  12. #include "mozilla/ReverseIterator.h"
  13. #include <stddef.h>
  14. namespace mozilla {
  15. template<typename T, size_t Length>
  16. class Array
  17. {
  18. T mArr[Length];
  19. public:
  20. Array() {}
  21. template <typename... Args>
  22. MOZ_IMPLICIT Array(Args&&... aArgs)
  23. : mArr{mozilla::Forward<Args>(aArgs)...}
  24. {
  25. static_assert(sizeof...(aArgs) == Length,
  26. "The number of arguments should be equal to the template parameter Length");
  27. }
  28. T& operator[](size_t aIndex)
  29. {
  30. MOZ_ASSERT(aIndex < Length);
  31. return mArr[aIndex];
  32. }
  33. const T& operator[](size_t aIndex) const
  34. {
  35. MOZ_ASSERT(aIndex < Length);
  36. return mArr[aIndex];
  37. }
  38. typedef T* iterator;
  39. typedef const T* const_iterator;
  40. typedef ReverseIterator<T*> reverse_iterator;
  41. typedef ReverseIterator<const T*> const_reverse_iterator;
  42. // Methods for range-based for loops.
  43. iterator begin() { return mArr; }
  44. const_iterator begin() const { return mArr; }
  45. const_iterator cbegin() const { return begin(); }
  46. iterator end() { return mArr + Length; }
  47. const_iterator end() const { return mArr + Length; }
  48. const_iterator cend() const { return end(); }
  49. // Methods for reverse iterating.
  50. reverse_iterator rbegin() { return reverse_iterator(end()); }
  51. const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); }
  52. const_reverse_iterator crbegin() const { return rbegin(); }
  53. reverse_iterator rend() { return reverse_iterator(begin()); }
  54. const_reverse_iterator rend() const { return const_reverse_iterator(begin()); }
  55. const_reverse_iterator crend() const { return rend(); }
  56. };
  57. template<typename T>
  58. class Array<T, 0>
  59. {
  60. public:
  61. T& operator[](size_t aIndex)
  62. {
  63. MOZ_CRASH("indexing into zero-length array");
  64. }
  65. const T& operator[](size_t aIndex) const
  66. {
  67. MOZ_CRASH("indexing into zero-length array");
  68. }
  69. };
  70. } /* namespace mozilla */
  71. #endif /* mozilla_Array_h */