Stratax
Scientific computing containers and operations
Loading...
Searching...
No Matches
Indexing.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <cstddef>
4
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{
29 strides.rank(),
30 shape.rank(),
31 "Shape, strides, and index must have the same rank.");
33 index.size(),
34 shape.rank(),
35 "Shape, strides, and index must 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 out of bounds.");
48 }
49
50 std::size_t term = 0;
51
52 try
53 {
55 *index_it,
56 *stride_it,
57 "Index offset overflow.");
58 }
59 catch (const Exceptions::DimensionError&)
60 {
61 throw Exceptions::IndexError("Index offset overflow.");
62 }
63
64 try
65 {
67 result,
68 term,
69 "Index offset overflow.");
70 }
71 catch (const Exceptions::DimensionError&)
72 {
73 throw Exceptions::IndexError("Index offset overflow.");
74 }
75 }
76
77 return result;
78}
std::size_t offset(const stratax::core::Shape &shape, const stratax::core::Strides &strides, const IndexContainer &index)
Computes a flat storage offset from a shape, strides, and index container.
Definition Indexing.hpp:23
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:20
std::size_t rank() const
Returns the number of stored dimensions.
Definition Shape.hpp:157
auto begin() noexcept
Returns an iterator to the first stored dimension.
Definition Shape.hpp:227
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:96
const std::size_t * begin() noexcept
Returns an iterator to the first stride value.
Definition Strides.hpp:164
std::size_t checked_multiply(std::size_t lhs, std::size_t rhs, const char *message)
Multiplies two sizes while checking for overflow.
void require_rank(std::size_t actual, std::size_t expected, const char *message)
Requires a rank value to match an expected rank.
std::size_t checked_add(std::size_t lhs, std::size_t rhs, const char *message)
Adds two sizes while checking for overflow.