1#ifndef SANISIZER_FLOAT_HPP
2#define SANISIZER_FLOAT_HPP
22template<
typename Integer_,
typename Float_>
23bool float_to_int_overflows(Float_ floored_x) {
24 constexpr auto output_precision = std::numeric_limits<Integer_>::digits;
25#ifndef SANISIZER_FLOAT_FORCE_FREXP
26 if constexpr(std::numeric_limits<Float_>::radix == 2) {
28 return floored_x != 0 && std::ilogb(floored_x) >= output_precision;
34 std::frexp(floored_x, &exp);
36 return exp > output_precision;
37#ifndef SANISIZER_FLOAT_FORCE_FREXP
57template<
typename Integer_,
typename Float_>
59 static_assert(std::is_floating_point<Float_>::value);
60 static_assert(std::is_integral<Integer_>::value);
62 if (!std::isfinite(x)) {
63 throw std::range_error(
"invalid conversion of non-finite value in sanisizer::from_float");
66 throw std::out_of_range(
"negative input value in sanisizer::from_float");
70 if (float_to_int_overflows<Integer_>(x)) {
71 throw std::overflow_error(
"overflow detected in sanisizer::from_float");
92template<
typename Float_,
typename Integer_>
97 constexpr auto xmax =
get_max<I<
decltype(x)> >();
98 if constexpr(xmax == 0) {
100 }
else if (val == 0) {
104 constexpr auto frad = std::numeric_limits<Float_>::radix;
105 constexpr auto fdig = std::numeric_limits<Float_>::digits;
106#ifndef SANISIZER_FLOAT_FORCE_MANUAL
107 if constexpr(frad == 2) {
108 if constexpr(std::numeric_limits<I<
decltype(val)> >::digits > fdig) {
109 if constexpr((xmax - 1) >> fdig) {
110 const auto y = (val - 1) >> fdig;
112 throw std::overflow_error(
"overflow detected in sanisizer::to_float");
119 I<
decltype(val)> working = val - 1;
120 for (I<
decltype(fdig)> d = 0; d < fdig && working; ++d) {
124 throw std::overflow_error(
"overflow detected in sanisizer::to_float");
126#ifndef SANISIZER_FLOAT_FORCE_MANUAL
Create compile-time attestations.
Sanitize sizes to avoid integer overflow.
Definition arithmetic.hpp:16
constexpr auto get_value(Value_ x)
Definition attest.hpp:105
Float_ to_float(Integer_ x)
Definition float.hpp:93
Integer_ from_float(Float_ x)
Definition float.hpp:58
constexpr auto get_max()
Definition attest.hpp:119