Stratax 0.3.1
Loading...
Searching...
No Matches
Normalize.hpp
1#pragma once
2
3#include <cstddef>
4
5#include <stratax/exceptions/Exceptions.hpp>
6
7namespace stratax::indexing {
8
9using size_type = std::size_t;
10using difference_type = std::ptrdiff_t;
11
12inline size_type normalize_index(
13 difference_type index,
14 size_type size)
15{
16 const size_type magnitude = index < 0
17 ? static_cast<size_type>(-(index + 1)) + 1
18 : 0;
19
20 if ((index >= 0 && static_cast<size_type>(index) >= size) ||
21 (index < 0 && magnitude > size))
22 {
23 throw Exceptions::IndexError("Index is out of bounds.");
24 }
25
26 return index >= 0 ? static_cast<size_type>(index) : size - magnitude;
27}
28
29} // namespace stratax::indexing