rippled
Loading...
Searching...
No Matches
safe_cast.h
1#pragma once
2
3#include <type_traits>
4
5namespace xrpl {
6
7// safe_cast adds compile-time checks to a static_cast to ensure that
8// the destination can hold all values of the source. This is particularly
9// handy when the source or destination is an enumeration type.
10
11template <class Src, class Dest>
14 (std::is_signed<Src>::value != std::is_signed<Dest>::value ? sizeof(Dest) > sizeof(Src)
15 : sizeof(Dest) >= sizeof(Src));
16
17template <class Dest, class Src>
19safe_cast(Src s) noexcept
20{
21 static_assert(std::is_signed_v<Dest> || std::is_unsigned_v<Src>, "Cannot cast signed to unsigned");
22 constexpr unsigned not_same = std::is_signed_v<Dest> != std::is_signed_v<Src>;
23 static_assert(sizeof(Dest) >= sizeof(Src) + not_same, "Destination is too small to hold all values of source");
24 return static_cast<Dest>(s);
25}
26
27template <class Dest, class Src>
29safe_cast(Src s) noexcept
30{
31 return static_cast<Dest>(safe_cast<std::underlying_type_t<Dest>>(s));
32}
33
34template <class Dest, class Src>
36safe_cast(Src s) noexcept
37{
38 return safe_cast<Dest>(static_cast<std::underlying_type_t<Src>>(s));
39}
40
41// unsafe_cast explicitly flags a static_cast as not necessarily able to hold
42// all values of the source. It includes a compile-time check so that if
43// underlying types become safe, it can be converted to a safe_cast.
44
45template <class Dest, class Src>
47unsafe_cast(Src s) noexcept
48{
49 static_assert(
51 "Only unsafe if casting signed to unsigned or "
52 "destination is too small");
53 return static_cast<Dest>(s);
54}
55
56template <class Dest, class Src>
58unsafe_cast(Src s) noexcept
59{
60 return static_cast<Dest>(unsafe_cast<std::underlying_type_t<Dest>>(s));
61}
62
63template <class Dest, class Src>
65unsafe_cast(Src s) noexcept
66{
67 return unsafe_cast<Dest>(static_cast<std::underlying_type_t<Src>>(s));
68}
69
70} // namespace xrpl
T is_same_v
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
constexpr std::enable_if_t< std::is_integral_v< Dest > &&std::is_integral_v< Src >, Dest > unsafe_cast(Src s) noexcept
Definition safe_cast.h:47
constexpr std::enable_if_t< std::is_integral_v< Dest > &&std::is_integral_v< Src >, Dest > safe_cast(Src s) noexcept
Definition safe_cast.h:19