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#include <limits>
6#include <stdexcept>
7#include <cstddef>
8#include <utility>
9
15namespace sanisizer {
16
20template<typename Size_>
21Size_ nd_offset_internal(Size_ extent, Size_ pos) {
22 return extent * pos;
23}
24
25template<typename Size_, typename... MoreArgs_>
26Size_ nd_offset_internal(Size_ extent, Size_ pos, MoreArgs_... more_args) {
27 return (pos + nd_offset_internal<Size_>(more_args...)) * extent;
28}
54template<typename Size_, typename First_, typename Second_, typename... Remaining_>
55Size_ nd_offset(First_ x1, First_ extent1, Second_ x2, Remaining_... remaining) {
56 // Note that we don't use Size_ in the function signature, even though everything is cast to Size_.
57 // This avoids inadvertent deduction of Size_ from the input types.
58 // The user is always forced to explicitly specify Size_ to avoid any risk of accidental overflow.
59 return static_cast<Size_>(x1) + nd_offset_internal<Size_>(extent1, x2, remaining...);
60}
61
62}
63
64#endif
65
Sanitize sizes to avoid integer overflow.
Definition arithmetic.hpp:14
Size_ nd_offset(First_ x1, First_ extent1, Second_ x2, Remaining_... remaining)
Definition nd_offset.hpp:55