From e05b522827f133335654619fe8d6c196d145dd45 Mon Sep 17 00:00:00 2001 From: Danny Robson Date: Wed, 1 Jan 2020 11:07:00 +1100 Subject: [PATCH] endian: add `readbe` to complement `readle` and `readhe` --- endian.hpp | 76 +++++++++++++++++++++++++++++------------------------- 1 file changed, 41 insertions(+), 35 deletions(-) diff --git a/endian.hpp b/endian.hpp index 405bc557..c16ba65b 100644 --- a/endian.hpp +++ b/endian.hpp @@ -73,41 +73,6 @@ namespace cruft { } - template < - typename T, - typename = std::enable_if_t< - std::is_integral_v - > - > - T readle (const void *_data) - { - auto data = reinterpret_cast (_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 readhe (const std::uint8_t *data) - { - std::aligned_union_t buffer; - memcpy (reinterpret_cast (&buffer), data, sizeof (T)); - return *reinterpret_cast (&buffer); - } - - //------------------------------------------------------------------------- #if defined(WORDS_BIGENDIAN) template constexpr T hton (T v) { return v; } @@ -132,6 +97,47 @@ namespace cruft { template T btol (T t) { return bswap (t); } template 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 readhe (u08 const *data) + { + std::aligned_union_t buffer; + memcpy (reinterpret_cast (&buffer), data, sizeof (T)); + return *reinterpret_cast (&buffer); + } + + + template < + typename T, + typename = std::enable_if_t< + std::is_integral_v + > + > + T readle (u08 const* ptr) + { + return ltoh (readhe (ptr)); + } + + + template < + typename T, + typename = std::enable_if_t< + std::is_integral_v + > + > + T readbe (u08 const* ptr) + { + return btoh (readhe (ptr)); + } + + namespace endian { //--------------------------------------------------------------------- // Uses the TIFF header values. Just because. Don't rely on this.