Stratax 0.2.0
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>
9
22template<typename IndexContainer>
23std::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
Shared runtime validation helpers.
Signals an invalid dimension count or dimension arithmetic failure.
Signals an invalid index access.
Stores a list of dimension lengths for an array shape.
Definition Shape.hpp:22
std::size_t rank() const
Returns the number of stored dimensions.
Definition Shape.hpp:176
iterator begin() noexcept
Returns an iterator to the first stored dimension.
Definition Shape.hpp:262
Stores strides for a shape in contiguous memory.
Definition Strides.hpp:23
std::size_t rank() const noexcept
Returns the number of dimensions represented by the strides.
Definition Strides.hpp:114
iterator begin() noexcept
Returns an iterator to the first stride value.
Definition Strides.hpp:182