endian: add an auto-converting endian type

This commit is contained in:
Danny Robson 2018-12-15 15:37:15 +11:00
parent 259c3de417
commit c573c9fa37

View File

@ -9,12 +9,15 @@
#ifndef __UTIL_ENDIAN_HPP #ifndef __UTIL_ENDIAN_HPP
#define __UTIL_ENDIAN_HPP #define __UTIL_ENDIAN_HPP
#include "std.hpp"
#include "types/bits.hpp" #include "types/bits.hpp"
#include <cstring> #include <cstring>
#include <cstdint> #include <cstdint>
#include <type_traits> #include <type_traits>
#include <iosfwd>
namespace cruft { namespace cruft {
//------------------------------------------------------------------------- //-------------------------------------------------------------------------
// CXX: Update using "if constexpr" when available. It doesn't seem to be // CXX: Update using "if constexpr" when available. It doesn't seem to be
@ -200,5 +203,42 @@ namespace cruft {
endian::scheme src; endian::scheme src;
}; };
namespace endian {
template <scheme StorageV, typename ValueT>
struct value {
operator ValueT () const
{
return convert<StorageV,scheme::native> (raw);
}
decltype(auto) operator+ () const { return +this->operator ValueT (); }
ValueT operator<< (size_t s) const { return convert<StorageV,scheme::native> (raw) << s; }
auto& operator= (ValueT const &val) { raw = convert<scheme::native,StorageV> (val); return *this; }
ValueT raw;
};
template <typename ValueT> using little = value<scheme::little,ValueT>;
template <typename ValueT> using big = value<scheme::big ,ValueT>;
template <scheme StorageV, typename ValueT>
std::ostream&
operator<< (std::ostream &os, value<StorageV,ValueT> const &val)
{
return os << +ValueT(val);
}
}
using bu16 = endian::big<u16>;
using bu32 = endian::big<u32>;
} }
#endif #endif