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::integer {
10 
11 namespace detail {
13 public:
14  static void SafeIntOnOverflow() __attribute__((noreturn)) { throw Overflow("integer overflow"); }
15 
16  static void SafeIntOnDivZero() __attribute__((noreturn)) { throw DivisionByZero("integer division by zero"); }
17 };
18 } // namespace detail
19 
20 template<typename T>
21 using safe = SafeInt<T, detail::SafeIntException>;
22 
23 } // namespace hilti::rt::integer
24 
25 // Needs to be a top level.
26 template<typename O, typename T>
27 inline auto operator<<(O& out, const hilti::rt::integer::safe<T>& x)
28  -> std::enable_if_t<std::is_base_of_v<std::ostream, O>, O>& {
29  if ( std::is_same<T, int8_t>() )
30  out << static_cast<int16_t>(x);
31  else if ( std::is_same<T, uint8_t>() )
32  out << static_cast<uint16_t>(x);
33  else
34  out << x.Ref();
35 
36  return out;
37 }
Definition: safe-int.h:9