sanisizer
Sanitize sizes to avoid integer overflow
Loading...
Searching...
No Matches
nd_offset.hpp
Go to the documentation of this file.
1#ifndef SANISIZER_ND_OFFSET_HPP
2#define SANISIZER_ND_OFFSET_HPP
3
4#include <type_traits>
5
6#include "generics.hpp"
7
13namespace sanisizer {
14
18template<typename Size_, typename Extent_, typename NextIndex_>
19constexpr Size_ nd_offset_internal(Extent_ extent, NextIndex_ pos) {
20 static_assert(std::is_integral<Size_>::value);
21 return get_value(extent) * get_value(pos);
22}
23
24template<typename Size_, typename Extent_, typename NextIndex_, typename... MoreArgs_>
25constexpr Size_ nd_offset_internal(Extent_ extent, NextIndex_ pos, MoreArgs_... more_args) {
26 static_assert(std::is_integral<Size_>::value);
27 return (get_value(pos) + nd_offset_internal<Size_>(more_args...)) * get_value(extent);
28}
60template<typename Size_, typename FirstIndex_, typename FirstExtent_, typename SecondIndex_, typename... Remaining_>
61constexpr Size_ nd_offset(FirstIndex_ x1, FirstExtent_ extent1, SecondIndex_ x2, Remaining_... remaining) {
62 static_assert(std::is_integral<Size_>::value);
63
64 // Note that we don't use Size_ in the function signature, even though everything is cast to Size_.
65 // This avoids inadvertent deduction of Size_ from the input types.
66 // The user is always forced to explicitly specify Size_ to avoid any risk of accidental overflow.
67 return static_cast<Size_>(get_value(x1)) + nd_offset_internal<Size_>(extent1, x2, remaining...);
68}
69
70}
71
72#endif
73
Generics for operating on integer representations.
Sanitize sizes to avoid integer overflow.
Definition Bounded.hpp:15
constexpr auto get_value(const Value_ x)
Definition generics.hpp:23
constexpr Size_ nd_offset(FirstIndex_ x1, FirstExtent_ extent1, SecondIndex_ x2, Remaining_... remaining)
Definition nd_offset.hpp:61