Stratax 0.3.1
Loading...
Searching...
No Matches
Slice.hpp
1// TODO: make size() overflow-safe for extreme ptrdiff_t bounds and steps.
2#pragma once
3
4#include <cstddef>
5
6#include <stratax/exceptions/Exceptions.hpp>
7
8namespace stratax::core {
9
30class Slice
31{
32public:
34 using size_type = std::size_t;
36 using difference_type = std::ptrdiff_t;
37
38private:
39 difference_type start_;
40 difference_type stop_;
41 difference_type step_;
42
43public:
57 : start_(start),
58 stop_(stop),
59 step_(step)
60 {
61 if (step == 0) {
62 throw Exceptions::IndexError("Slice step cannot be zero.");
63 }
64 }
65
67 [[nodiscard]] difference_type start() const noexcept {return start_;}
69 [[nodiscard]] difference_type stop() const noexcept {return stop_;}
71 [[nodiscard]] difference_type step() const noexcept {return step_;}
72
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 difference_type distance = stop_ - start_;
97 return static_cast<size_type>((distance + step_ - 1) / step_);
98 }
99
100 if (start_ <= stop_)
101 {
102 return 0;
103 }
104
105 const difference_type stride = -step_;
106 const difference_type distance = start_ - stop_;
107 return static_cast<size_type>((distance + stride - 1) / stride);
108 }
109
111 [[nodiscard]] bool empty() const noexcept {return size() == 0;}
112
119 [[nodiscard]] bool operator==(const Slice& other) const noexcept {return start_ == other.start_ && stop_ == other.stop_ && step_ == other.step_;}
120};
121
122}
Describes a signed, strided half-open index range.
Definition Slice.hpp:31
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:67
bool operator==(const Slice &other) const noexcept
Compares two slices by their stored bounds and step.
Definition Slice.hpp:119
difference_type stop() const noexcept
Returns the raw exclusive stop bound.
Definition Slice.hpp:69
std::size_t size_type
Unsigned type used for the number of selected indices.
Definition Slice.hpp:34
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:56
bool empty() const noexcept
Reports whether the raw range selects no indices.
Definition Slice.hpp:111
difference_type step() const noexcept
Returns the nonzero signed step.
Definition Slice.hpp:71
std::ptrdiff_t difference_type
Signed type used for bounds and step values.
Definition Slice.hpp:36