R-Type
R-Type project
ArraySegment.hpp
1 #pragma once
2 
3 #include "Array.hpp"
4 #include <stdexcept>
5 #include <memory>
6 
7 namespace KapMirror {
8  template <typename T>
9  class ArraySegment {
10  private:
11  T* array;
12  int offset;
13  int size;
14 
15  public:
16  ArraySegment() {
17  array = nullptr;
18  offset = 0;
19  size = 0;
20  }
21 
22  explicit ArraySegment(T* _array, int _size) {
23  array = Array::copyArray(_array, _size);
24  offset = 0;
25  size = _size;
26  }
27 
28  explicit ArraySegment(T* _array, int _offset, int _size) {
29  array = Array::copyArray(_array, _size);
30  offset = _offset;
31  size = _size - _offset;
32  }
33 
34  ~ArraySegment() { delete[] array; }
35 
40  T* toArray() const { return array + offset; }
41 
42  explicit operator T*() const { return array + offset; }
43 
48  int getOffset() const { return offset; }
49 
54  int getSize() const { return size; }
55 
56  T& operator[](int index) {
57  if (index < 0 || index >= size) {
58  throw std::out_of_range("index is out of range");
59  }
60  return array[offset + index];
61  }
62 
63  bool operator==(ArraySegment<T> const& other) {
64  for (int i = 0; i < std::min(size, other.size); i++) {
65  if (array[offset + i] != other.array[other.offset + i]) {
66  return false;
67  }
68  }
69  return true;
70  }
71 
72  bool operator!=(ArraySegment<T> const& other) { return *this != other; }
73 
74  ArraySegment<T>& operator=(ArraySegment<T> const& other) {
75  array = Array::copyArray(other.array, other.size);
76  offset = other.offset;
77  size = other.size;
78  return *this;
79  }
80 
81  static std::shared_ptr<ArraySegment<T>> createArraySegment(T* array, int size) {
82  return std::make_shared<ArraySegment<T>>(array, size);
83  }
84 
85  static std::shared_ptr<ArraySegment<T>> createArraySegment(T* array, int offset, int size) {
86  return std::make_shared<ArraySegment<T>>(array, offset, size);
87  }
88  };
89 } // namespace KapMirror
KapMirror::ArraySegment::getOffset
int getOffset() const
Get the offset of the array.
Definition: ArraySegment.hpp:48
KapMirror::ArraySegment::toArray
T * toArray() const
Get the array.
Definition: ArraySegment.hpp:40
KapMirror::ArraySegment::getSize
int getSize() const
Get the size of the array.
Definition: ArraySegment.hpp:54
KapMirror::Array::copyArray
static T * copyArray(T *array, int size)
Copy an array.
Definition: Array.hpp:33
KapMirror::ArraySegment
Definition: ArraySegment.hpp:9