Stratax 0.3.1
Loading...
Searching...
No Matches
Normalize.hpp
1#pragma once
2
3#include <cstddef>
4#include <string>
5
6#include <stratax/exceptions/Exceptions.hpp>
7
8using size_type = std::size_t;
9using difference_type = std::ptrdiff_t;
10
11namespace stratax::indexing {
12
13inline size_type normalize_index(
14 difference_type index,
15 size_type size
16 )
17{
18 if (index >= 0)
19 {
20 const size_type normalized = static_cast<size_type>(index);
21
22 if (normalized >= size)
23 {
24 throw Exceptions::IndexError("Index " + std::to_string(index) +
25 " is out of bounds for array with size " + std::to_string(size) + ".");
26 }
27
28 return normalized;
29 }
30
31 const size_type magnitude =
32 static_cast<size_type>(-(index + 1)) + 1;
33
34 if (magnitude > size)
35 {
36 throw Exceptions::IndexError("Index " + std::to_string(index) +
37 " is out of bounds for array with size " + std::to_string(size) + ".");
38 }
39
40 return size - magnitude;
41}
42
43} // namespace stratax::indexing