CBMC
narrow.h
Go to the documentation of this file.
1 /*******************************************************************\
2 
3 Module: Narrowing conversion functions
4 
5 Author: Diffblue Ltd.
6 
7 \*******************************************************************/
8 
9 #ifndef CPROVER_UTIL_NARROW_H
10 #define CPROVER_UTIL_NARROW_H
11 
12 #include <type_traits>
13 
14 #include "invariant.h"
15 
18 template <typename output_type, typename input_type>
19 output_type narrow_cast(input_type value)
20 {
21  static_assert(
22  std::is_arithmetic<input_type>::value &&
23  std::is_arithmetic<output_type>::value,
24  "narrow_cast is intended only for numeric conversions");
25  return static_cast<output_type>(value);
26 }
27 
33 template <typename output_type, typename input_type>
34 output_type narrow(input_type input)
35 {
36  const auto output = static_cast<output_type>(input);
37  INVARIANT(static_cast<input_type>(output) == input, "Data loss detected");
38  return output;
39 }
40 
43 template <typename output_type, typename input_type>
44 output_type narrow_or_throw_out_of_range(input_type input)
45 {
46  auto const result = narrow_cast<input_type>(input);
47  if(result != input)
48  {
49  throw std::out_of_range{"narrowing gave a different value than expected"};
50  }
51  return result;
52 }
53 
54 #endif // CPROVER_UTIL_NARROW_H
output_type narrow(input_type input)
Run-time checked narrowing cast.
Definition: narrow.h:34
output_type narrow_or_throw_out_of_range(input_type input)
Run-time checked narrow cast.
Definition: narrow.h:44
output_type narrow_cast(input_type value)
Alias for static_cast intended to be used for numeric casting Rationale: Easier to grep than static_c...
Definition: narrow.h:19
#define INVARIANT(CONDITION, REASON)
This macro uses the wrapper function 'invariant_violated_string'.
Definition: invariant.h:423