Last active
February 19, 2020 22:01
-
-
Save jtsylve/5af80d12a72a8f93c34ed763c0dd3821 to your computer and use it in GitHub Desktop.
Automatically convert on-disk mixed endian types to native
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <algorithm> | |
#include <bit> | |
#include <cstddef> | |
#include <type_traits> | |
template <typename T, std::endian endianess, | |
typename = std::enable_if_t<std::is_scalar_v<T>>> | |
class endian { | |
public: | |
constexpr endian() noexcept = default; | |
endian(const T &val) noexcept : _val{swap(val)} {} | |
operator T() const noexcept { return swap(_val); } | |
private: | |
static T swap(T val) noexcept { | |
if constexpr (endianess == std::endian::native) { | |
return val; | |
} | |
using bytes_type = std::byte[sizeof(T)]; | |
static_assert(sizeof(bytes_type) == sizeof(T)); | |
auto &bytes = reinterpret_cast<bytes_type &>(val); | |
std::reverse(std::begin(bytes), std::end(bytes)); | |
return val; | |
} | |
T _val{}; | |
}; | |
template <typename T> | |
using big_endian = endian<T, std::endian::big>; | |
template <typename T> | |
using little_endian = endian<T, std::endian::little>; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment