Stratax 0.2.0
Loading...
Searching...
No Matches
Slice.hpp
1#pragma once
2
3#include "Exceptions.hpp"
4
5#include <cstddef>
6
7namespace stratax::core {
8
15class Slice
16{
17private:
18 std::ptrdiff_t start_;
19 std::ptrdiff_t stop_;
20 std::ptrdiff_t step_;
21
22public:
34 Slice(std::ptrdiff_t start, std::ptrdiff_t stop, std::ptrdiff_t step = 1)
35 : start_(start),
36 stop_(stop),
37 step_(step)
38 {
39 if (step == 0) {
40 throw Exceptions::IndexError("Slice step cannot be zero.");
41 }
42 }
43
49 [[nodiscard]] std::ptrdiff_t start() const noexcept
50 {
51 return start_;
52 }
53
59 [[nodiscard]] std::ptrdiff_t stop() const noexcept
60 {
61 return stop_;
62 }
63
69 [[nodiscard]] std::ptrdiff_t step() const noexcept
70 {
71 return step_;
72 }
73
79 [[nodiscard]] std::size_t size() const noexcept
80 {
81 if (step_ > 0)
82 {
83 if (start_ >= stop_)
84 {
85 return 0;
86 }
87
88 const std::ptrdiff_t distance = stop_ - start_;
89 return static_cast<std::size_t>((distance + step_ - 1) / step_);
90 }
91
92 if (start_ <= stop_)
93 {
94 return 0;
95 }
96
97 const std::ptrdiff_t stride = -step_;
98 const std::ptrdiff_t distance = start_ - stop_;
99 return static_cast<std::size_t>((distance + stride - 1) / stride);
100 }
101
107 [[nodiscard]] bool empty() const noexcept
108 {
109 return size() == 0;
110 }
111
119 [[nodiscard]] bool operator==(const Slice& other) const noexcept
120 {
121 return start_ == other.start_ && stop_ == other.stop_ && step_ == other.step_;
122 }
123
131 [[nodiscard]] bool operator!=(const Slice& other) const noexcept
132 {
133 return !(*this == other);
134 }
135};
136
137}
Signals an invalid index access.
std::ptrdiff_t start() const noexcept
Returns the first index in the slice.
Definition Slice.hpp:49
bool operator==(const Slice &other) const noexcept
Compares two slices for identical bounds and step.
Definition Slice.hpp:119
std::size_t size() const noexcept
Returns the number of indices covered by the slice.
Definition Slice.hpp:79
Slice(std::ptrdiff_t start, std::ptrdiff_t stop, std::ptrdiff_t step=1)
Creates a half-open strided slice range.
Definition Slice.hpp:34
bool empty() const noexcept
Returns whether the slice selects no elements.
Definition Slice.hpp:107
bool operator!=(const Slice &other) const noexcept
Returns whether two slices have different bounds.
Definition Slice.hpp:131
std::ptrdiff_t step() const noexcept
Returns the stride between selected indices.
Definition Slice.hpp:69
std::ptrdiff_t stop() const noexcept
Returns the index one past the end of the slice.
Definition Slice.hpp:59