array.hpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #pragma once
  2. #include <nall/array-span.hpp>
  3. #include <nall/array-view.hpp>
  4. #include <nall/range.hpp>
  5. #include <nall/view.hpp>
  6. namespace nall {
  7. template<typename T> struct array;
  8. //usage: int x[256] => array<int[256]> x
  9. template<typename T, uint Size> struct array<T[Size]> {
  10. array() = default;
  11. array(const initializer_list<T>& source) {
  12. uint index = 0;
  13. for(auto& value : source) {
  14. operator[](index++) = value;
  15. }
  16. }
  17. operator array_span<T>() {
  18. return {data(), size()};
  19. }
  20. operator array_view<T>() const {
  21. return {data(), size()};
  22. }
  23. alwaysinline auto operator[](uint index) -> T& {
  24. #ifdef DEBUG
  25. struct out_of_bounds {};
  26. if(index >= Size) throw out_of_bounds{};
  27. #endif
  28. return values[index];
  29. }
  30. alwaysinline auto operator[](uint index) const -> const T& {
  31. #ifdef DEBUG
  32. struct out_of_bounds {};
  33. if(index >= Size) throw out_of_bounds{};
  34. #endif
  35. return values[index];
  36. }
  37. alwaysinline auto operator()(uint index, const T& fallback = {}) const -> const T& {
  38. if(index >= Size) return fallback;
  39. return values[index];
  40. }
  41. auto fill(const T& fill = {}) -> array& {
  42. for(auto& value : values) value = fill;
  43. return *this;
  44. }
  45. auto data() -> T* { return values; }
  46. auto data() const -> const T* { return values; }
  47. auto size() const -> uint { return Size; }
  48. auto begin() -> T* { return &values[0]; }
  49. auto end() -> T* { return &values[Size]; }
  50. auto begin() const -> const T* { return &values[0]; }
  51. auto end() const -> const T* { return &values[Size]; }
  52. private:
  53. T values[Size];
  54. };
  55. template<typename T, T... p> auto from_array(uint index) -> T {
  56. static const array<T[sizeof...(p)]> table{p...};
  57. struct out_of_bounds {};
  58. #if defined(DEBUG)
  59. if(index >= sizeof...(p)) throw out_of_bounds{};
  60. #endif
  61. return table[index];
  62. }
  63. template<int64_t... p> auto from_array(uint index) -> int64_t {
  64. static const array<int64_t[sizeof...(p)]> table{p...};
  65. struct out_of_bounds {};
  66. #if defined(DEBUG)
  67. if(index >= sizeof...(p)) throw out_of_bounds{};
  68. #endif
  69. return table[index];
  70. }
  71. }