sanisizer
Sanitize sizes to avoid integer overflow
Loading...
Searching...
No Matches
cap.hpp
Go to the documentation of this file.
1#ifndef SANISIZER_CAP_HPP
2#define SANISIZER_CAP_HPP
3
4#include <limits>
5#include <type_traits>
6
7#include "utils.hpp"
8#include "attest.hpp"
9
15namespace sanisizer {
16
29template<typename Dest_, typename Value_>
30constexpr Dest_ cap(Value_ x) {
31 static_assert(std::is_integral<Dest_>::value);
32 constexpr auto maxed = std::numeric_limits<Dest_>::max();
33 constexpr auto umaxed = as_unsigned(maxed);
34
35 const auto val = get_value(x);
36 if constexpr(umaxed >= as_unsigned(get_max<Value_>())) {
37 return val;
38 } else if (umaxed >= as_unsigned(val)) {
39 return val;
40 } else {
41 return maxed;
42 }
43}
44
45}
46
47#endif
Create compile-time attestations.
Sanitize sizes to avoid integer overflow.
Definition arithmetic.hpp:16
constexpr auto get_value(Value_ x)
Definition attest.hpp:105
constexpr auto get_max()
Definition attest.hpp:119
constexpr Dest_ cap(Value_ x)
Definition cap.hpp:30