Stratax
0.2.0
Toggle main menu visibility
Loading...
Searching...
No Matches
Slice.hpp
1
#pragma once
2
3
#include "Exceptions.hpp"
4
5
#include <cstddef>
6
7
namespace
stratax::core {
8
15
class
Slice
16
{
17
private
:
18
std::ptrdiff_t start_;
19
std::ptrdiff_t stop_;
20
std::ptrdiff_t step_;
21
22
public
:
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
}
Exceptions::IndexError
Signals an invalid index access.
Definition
Exceptions.hpp:30
stratax::core::Slice::start
std::ptrdiff_t start() const noexcept
Returns the first index in the slice.
Definition
Slice.hpp:49
stratax::core::Slice::operator==
bool operator==(const Slice &other) const noexcept
Compares two slices for identical bounds and step.
Definition
Slice.hpp:119
stratax::core::Slice::size
std::size_t size() const noexcept
Returns the number of indices covered by the slice.
Definition
Slice.hpp:79
stratax::core::Slice::Slice
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
stratax::core::Slice::empty
bool empty() const noexcept
Returns whether the slice selects no elements.
Definition
Slice.hpp:107
stratax::core::Slice::operator!=
bool operator!=(const Slice &other) const noexcept
Returns whether two slices have different bounds.
Definition
Slice.hpp:131
stratax::core::Slice::step
std::ptrdiff_t step() const noexcept
Returns the stride between selected indices.
Definition
Slice.hpp:69
stratax::core::Slice::stop
std::ptrdiff_t stop() const noexcept
Returns the index one past the end of the slice.
Definition
Slice.hpp:59
include
stratax
core
Slice.hpp
Generated by
1.17.0