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