2015-11-06 14:49:24 +00:00
|
|
|
#pragma once
|
|
|
|
|
2017-06-22 05:14:49 +00:00
|
|
|
#include <string.h>
|
|
|
|
#include <algorithm>
|
2015-11-06 14:49:24 +00:00
|
|
|
#include <type_traits>
|
|
|
|
|
|
|
|
|
|
|
|
namespace ext
|
|
|
|
{
|
2017-06-06 17:10:04 +00:00
|
|
|
/** \brief Returns value `from` converted to type `To` while retaining bit representation.
|
2017-06-21 17:16:24 +00:00
|
|
|
* `To` and `From` must satisfy `CopyConstructible`.
|
|
|
|
*/
|
2017-06-06 17:10:04 +00:00
|
|
|
template <typename To, typename From>
|
|
|
|
std::decay_t<To> bit_cast(const From & from)
|
|
|
|
{
|
2017-06-21 17:16:24 +00:00
|
|
|
To res {};
|
|
|
|
memcpy(&res, &from, std::min(sizeof(res), sizeof(from)));
|
|
|
|
return res;
|
2017-06-06 17:10:04 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
/** \brief Returns value `from` converted to type `To` while retaining bit representation.
|
2017-06-21 17:16:24 +00:00
|
|
|
* `To` and `From` must satisfy `CopyConstructible`.
|
|
|
|
*/
|
2017-06-06 17:10:04 +00:00
|
|
|
template <typename To, typename From>
|
|
|
|
std::decay_t<To> safe_bit_cast(const From & from)
|
|
|
|
{
|
|
|
|
static_assert(sizeof(To) == sizeof(From), "bit cast on types of different width");
|
2017-06-21 17:16:24 +00:00
|
|
|
return bit_cast<To, From>(from);
|
2017-06-06 17:10:04 +00:00
|
|
|
};
|
2015-11-06 14:49:24 +00:00
|
|
|
}
|