Stratax
0.2.0
Toggle main menu visibility
Loading...
Searching...
No Matches
Indexing.hpp
1
#pragma once
2
3
#include <cstddef>
4
5
#include <stratax/core/Exceptions.hpp>
6
#include <stratax/core/containers/Strides.hpp>
7
#include <stratax/core/containers/Shape.hpp>
8
#include <
stratax/core/validation/Validation.hpp
>
9
22
template
<
typename
IndexContainer>
23
std::size_t offset(
24
const
stratax::core::Shape
& shape,
25
const
stratax::core::Strides
& strides,
26
const
IndexContainer& index)
27
{
28
stratax::core::validation::require_rank(
29
strides.
rank
(),
30
shape.
rank
(),
31
"Indexing requires shape, strides, and index to have the same rank."
);
32
stratax::core::validation::require_rank(
33
index.size(),
34
shape.
rank
(),
35
"Indexing requires shape, strides, and index to have the same rank."
);
36
37
std::size_t result = 0;
38
39
auto
shape_it = shape.
begin
();
40
auto
stride_it = strides.
begin
();
41
auto
index_it = index.begin();
42
43
for
(; index_it != index.end(); ++shape_it, ++stride_it, ++index_it)
44
{
45
if
(*index_it >= *shape_it)
46
{
47
throw
Exceptions::IndexError
(
"Index component is out of bounds."
);
48
}
49
50
std::size_t term = 0;
51
52
try
53
{
54
term = stratax::core::validation::checked_multiply(
55
*index_it,
56
*stride_it,
57
"Index offset multiplication overflow."
);
58
}
59
catch
(
const
Exceptions::DimensionError
&)
60
{
61
throw
Exceptions::IndexError
(
"Index offset multiplication overflow."
);
62
}
63
64
try
65
{
66
result = stratax::core::validation::checked_add(
67
result,
68
term,
69
"Index offset addition overflow."
);
70
}
71
catch
(
const
Exceptions::DimensionError
&)
72
{
73
throw
Exceptions::IndexError
(
"Index offset addition overflow."
);
74
}
75
}
76
77
return
result;
78
}
79
Validation.hpp
Shared runtime validation helpers.
Exceptions::DimensionError
Signals an invalid dimension count or dimension arithmetic failure.
Definition
Exceptions.hpp:23
Exceptions::IndexError
Signals an invalid index access.
Definition
Exceptions.hpp:30
stratax::core::Shape
Stores a list of dimension lengths for an array shape.
Definition
Shape.hpp:22
stratax::core::Shape::rank
std::size_t rank() const
Returns the number of stored dimensions.
Definition
Shape.hpp:176
stratax::core::Shape::begin
iterator begin() noexcept
Returns an iterator to the first stored dimension.
Definition
Shape.hpp:262
stratax::core::Strides
Stores strides for a shape in contiguous memory.
Definition
Strides.hpp:23
stratax::core::Strides::rank
std::size_t rank() const noexcept
Returns the number of dimensions represented by the strides.
Definition
Strides.hpp:114
stratax::core::Strides::begin
iterator begin() noexcept
Returns an iterator to the first stride value.
Definition
Strides.hpp:182
include
stratax
core
ops
Indexing.hpp
Generated by
1.17.0