endian: add readbe to complement readle and readhe

This commit is contained in:
Danny Robson 2020-01-01 11:07:00 +11:00
parent 61881b7c8f
commit e05b522827

View File

@ -73,41 +73,6 @@ namespace cruft {
} }
template <
typename T,
typename = std::enable_if_t<
std::is_integral_v<T>
>
>
T readle (const void *_data)
{
auto data = reinterpret_cast<const uint8_t*> (_data);
T value = 0;
for (size_t i = 0; i < sizeof (value); ++i)
value |= T{data[i]} << (i * 8);
return value;
}
/// read bytes from a supplied data pointer and return an integer using
/// host endian layout.
template <
typename T,
typename = std::enable_if_t<
std::is_integral_v<T>
>
>
T readhe (const std::uint8_t *data)
{
std::aligned_union_t <sizeof (T), T> buffer;
memcpy (reinterpret_cast<char *> (&buffer), data, sizeof (T));
return *reinterpret_cast<const T*> (&buffer);
}
//------------------------------------------------------------------------- //-------------------------------------------------------------------------
#if defined(WORDS_BIGENDIAN) #if defined(WORDS_BIGENDIAN)
template <typename T> constexpr T hton (T v) { return v; } template <typename T> constexpr T hton (T v) { return v; }
@ -132,6 +97,47 @@ namespace cruft {
template <typename T> T btol (T t) { return bswap (t); } template <typename T> T btol (T t) { return bswap (t); }
template <typename T> T ltob (T t) { return bswap (t); } template <typename T> T ltob (T t) { return bswap (t); }
/// read bytes from a supplied data pointer and return an integer using
/// host endian layout.
template <
typename T,
typename = std::enable_if_t<
std::is_integral_v<T>
>
>
T readhe (u08 const *data)
{
std::aligned_union_t <sizeof (T), T> buffer;
memcpy (reinterpret_cast<char *> (&buffer), data, sizeof (T));
return *reinterpret_cast<const T*> (&buffer);
}
template <
typename T,
typename = std::enable_if_t<
std::is_integral_v<T>
>
>
T readle (u08 const* ptr)
{
return ltoh (readhe<T> (ptr));
}
template <
typename T,
typename = std::enable_if_t<
std::is_integral_v<T>
>
>
T readbe (u08 const* ptr)
{
return btoh (readhe<T> (ptr));
}
namespace endian { namespace endian {
//--------------------------------------------------------------------- //---------------------------------------------------------------------
// Uses the TIFF header values. Just because. Don't rely on this. // Uses the TIFF header values. Just because. Don't rely on this.