ArrayView.hpp
1 #pragma once
2 #include <cassert>
3 #include <cstddef>
4 
5 #if defined(_WIN32)
6 #include <malloc.h>
7 #else
8 #include <alloca.h>
9 #endif
10 
11 namespace score
12 {
13 template <typename T>
15 {
16 private:
17  T* m_ptr{};
18  std::size_t m_size{};
19 
20 public:
21  using value_type = T;
22  dynarray_impl(T* t, std::size_t size)
23  : m_ptr{t}
24  , m_size{size}
25  {
26  }
27 
28  dynarray_impl(const dynarray_impl& other) = default;
29  dynarray_impl(dynarray_impl&& other) = default;
30  dynarray_impl& operator=(const dynarray_impl& other) = default;
31  dynarray_impl& operator=(dynarray_impl&& other) = default;
32 
33  auto begin() const { return m_ptr; }
34  auto end() const { return m_ptr + m_size; }
35 
36  auto size() const { return m_size; }
37 
38  T& operator[](std::size_t pos) const
39  {
40  assert(m_ptr);
41  assert(pos < m_size);
42  return *(m_ptr + pos);
43  }
44 };
45 
46 #define make_dynarray(Type, Count) \
47  score::dynarray_impl<Type> \
48  { \
49  (Type*)alloca(sizeof(Type) * Count), Count \
50  }
51 
52 template <typename T>
54 {
55 private:
56  T* m_ptr{};
57  std::size_t m_size{};
58  std::size_t m_capacity{};
59 
60 public:
61  using value_type = T;
62  using iterator = T*;
63  using const_iterator = T*;
64 
65  dynvector_impl(T* t, std::size_t capacity)
66  : m_ptr{t}
67  , m_capacity{capacity}
68  {
69  }
70 
71  dynvector_impl(const dynvector_impl& other) = default;
72  dynvector_impl(dynvector_impl&& other) = default;
73  dynvector_impl& operator=(const dynvector_impl& other) = default;
74  dynvector_impl& operator=(dynvector_impl&& other) = default;
75 
76  iterator begin() const { return m_ptr; }
77  iterator end() const { return m_ptr + m_size; }
78 
79  std::size_t size() const { return m_size; }
80 
81  T& operator[](std::size_t pos) const
82  {
83  assert(m_ptr);
84  assert(pos < m_size);
85  return *(m_ptr + pos);
86  }
87 
88  void push_back(T&& t)
89  {
90  assert(m_size + 1 <= m_capacity);
91  *(m_ptr + m_size) = std::move(t);
92  m_size++;
93  }
94 
95  void push_back(const T& t)
96  {
97  assert(m_size + 1 <= m_capacity);
98  *(m_ptr + m_size) = t;
99  m_size++;
100  }
101 };
102 
103 #define make_dynvector(Type, Count) \
104  score::dynvector_impl<Type> \
105  { \
106  (Type*)alloca(sizeof(Type) * Count), Count \
107  }
108 }
Definition: ArrayView.hpp:15
Definition: ArrayView.hpp:54
Base toolkit upon which the software is built.
Definition: Application.cpp:90