Spicy
safe-int.h
1 // Copyright (c) 2020-2021 by the Zeek Project. See LICENSE for details.
2 
3 #pragma once
4 
5 #define SAFEINT_DISABLE_ADDRESS_OPERATOR
6 #include <hilti/rt/3rdparty/SafeInt/SafeInt.hpp>
7 #include <hilti/rt/exception.h>
8 
9 namespace hilti::rt {
10 namespace integer {
11 
12 namespace detail {
14 public:
15  static void SafeIntOnOverflow() __attribute__((noreturn)) { throw Overflow("integer overflow"); }
16 
17  static void SafeIntOnDivZero() __attribute__((noreturn)) { throw DivisionByZero("integer division by zero"); }
18 };
19 } // namespace detail
20 
21 template<typename T>
22 using safe = SafeInt<T, detail::SafeIntException>;
23 
24 } // namespace integer
25 } // namespace hilti::rt
26 
27 // Needs to be a top level.
28 template<typename O, typename T>
29 inline auto operator<<(O& out, const hilti::rt::integer::safe<T>& x)
30  -> std::enable_if_t<std::is_base_of_v<std::ostream, O>, O>& {
31  if ( std::is_same<T, int8_t>() )
32  out << static_cast<int16_t>(x);
33  else if ( std::is_same<T, uint8_t>() )
34  out << static_cast<uint16_t>(x);
35  else
36  out << x.Ref();
37 
38  return out;
39 }
Definition: any.h:7