Skip to content

Instantly share code, notes, and snippets.

@jtsylve
Last active February 19, 2020 22:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jtsylve/5af80d12a72a8f93c34ed763c0dd3821 to your computer and use it in GitHub Desktop.
Save jtsylve/5af80d12a72a8f93c34ed763c0dd3821 to your computer and use it in GitHub Desktop.
Automatically convert on-disk mixed endian types to native
#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