Stratax 0.4.0rc1
Loading...
Searching...
No Matches
Slice.hpp
Go to the documentation of this file.
1
4#pragma once
5
6#include <cstddef>
7
9
10namespace stratax::core {
11
32class Slice
33{
34public:
36 using size_type = std::size_t;
38 using difference_type = std::ptrdiff_t;
39
40private:
41 difference_type start_;
42 difference_type stop_;
43 difference_type step_;
44
45public:
59 : start_(start),
60 stop_(stop),
61 step_(step)
62 {
63 if (step == 0) {
64 throw Exceptions::IndexError("Slice step cannot be zero.");
65 }
66 }
67
69 [[nodiscard]] difference_type start() const noexcept {return start_;}
71 [[nodiscard]] difference_type stop() const noexcept {return stop_;}
73 [[nodiscard]] difference_type step() const noexcept {return step_;}
74
87 [[nodiscard]] size_type size() const noexcept
88 {
89 if (step_ > 0)
90 {
91 if (start_ >= stop_)
92 {
93 return 0;
94 }
95
96 const size_type distance = static_cast<size_type>(stop_) - static_cast<size_type>(start_);
97 const size_type stride = static_cast<size_type>(step_);
98 return 1 + (distance - 1) / stride;
99 }
100
101 if (start_ <= stop_)
102 {
103 return 0;
104 }
105
106 const size_type stride = size_type{0} - static_cast<size_type>(step_);
107 const size_type distance = static_cast<size_type>(start_) - static_cast<size_type>(stop_);
108 return 1 + (distance - 1) / stride;
109 }
110
112 [[nodiscard]] bool empty() const noexcept {return size() == 0;}
113
120 [[nodiscard]] bool operator==(const Slice& other) const noexcept {return start_ == other.start_ && stop_ == other.stop_ && step_ == other.step_;}
121};
122
123}
Stratax exception types derived from std::runtime_error.
Index or slice cannot be used for the requested access.
Describes a signed, strided half-open index range.
Definition Slice.hpp:33
size_type size() const noexcept
Returns the number of indices described by the raw range.
Definition Slice.hpp:87
difference_type start() const noexcept
Returns the raw inclusive start bound.
Definition Slice.hpp:69
bool operator==(const Slice &other) const noexcept
Compares two slices by their stored bounds and step.
Definition Slice.hpp:120
difference_type stop() const noexcept
Returns the raw exclusive stop bound.
Definition Slice.hpp:71
std::size_t size_type
Unsigned type used for the number of selected indices.
Definition Slice.hpp:36
Slice(difference_type start, difference_type stop, difference_type step=1)
Constructs a slice from raw half-open bounds and a step.
Definition Slice.hpp:58
bool empty() const noexcept
Reports whether the raw range selects no indices.
Definition Slice.hpp:112
difference_type step() const noexcept
Returns the nonzero signed step.
Definition Slice.hpp:73
std::ptrdiff_t difference_type
Signed type used for bounds and step values.
Definition Slice.hpp:38