sanisizer
Sanitize sizes to avoid integer overflow
Loading...
Searching...
No Matches
cast.hpp
Go to the documentation of this file.
1#ifndef SANISIZER_CAST_HPP
2#define SANISIZER_CAST_HPP
3
4#include "utils.hpp"
5#include "comparisons.hpp"
6#include "generics.hpp"
7
13namespace sanisizer {
14
21template<typename Dest_, typename Value_>
22constexpr bool can_cast(Value_ x) {
23 static_assert(std::is_integral<Dest_>::value);
24 constexpr auto dest_maxed = get_max<Dest_>();
25 if constexpr(is_less_than_or_equal(get_max<Value_>(), dest_maxed)) {
26 return true;
27 } else {
28 return is_less_than_or_equal(get_value(x), dest_maxed);
29 }
30}
31
35template<typename Dest_, typename Value_>
36constexpr bool check_overflow(Value_ x) {
37 if (!can_cast<Dest_>(x)) {
38 throw std::overflow_error("detected " + failure<Dest_>() + " for integer cast");
39 }
40 return false;
41}
58template<typename Dest_, typename Value_>
59constexpr Dest_ cast(Value_ x) {
60 check_overflow<Dest_>(x);
61 return get_value(x);
62}
63
64}
65
66#endif
Signedness-safe integer comparisons.
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 auto get_max()
Definition generics.hpp:39
constexpr bool can_cast(Value_ x)
Definition cast.hpp:22
constexpr bool is_less_than_or_equal(Left_ left, Right_ right)
Definition comparisons.hpp:75
constexpr Dest_ cast(Value_ x)
Definition cast.hpp:59