1#pragma once
2
3#include <string.h>
4#include <algorithm>
5#include <type_traits>
6
7
8namespace ext
9{
10 /** \brief Returns value `from` converted to type `To` while retaining bit representation.
11 * `To` and `From` must satisfy `CopyConstructible`.
12 */
13 template <typename To, typename From>
14 std::decay_t<To> bit_cast(const From & from)
15 {
16 To res {};
17 memcpy(static_cast<void*>(&res), &from, std::min(sizeof(res), sizeof(from)));
18 return res;
19 }
20
21 /** \brief Returns value `from` converted to type `To` while retaining bit representation.
22 * `To` and `From` must satisfy `CopyConstructible`.
23 */
24 template <typename To, typename From>
25 std::decay_t<To> safe_bit_cast(const From & from)
26 {
27 static_assert(sizeof(To) == sizeof(From), "bit cast on types of different width");
28 return bit_cast<To, From>(from);
29 }
30}
31