From: Francis Deslauriers Date: Wed, 25 May 2022 15:20:53 +0000 (-0400) Subject: cpp-common: add `readFixedLenInt()` function X-Git-Url: http://git.efficios.com/?a=commitdiff_plain;h=e0a3ddd47246163b70f9764c0f147807ff1fc0ea;p=babeltrace.git cpp-common: add `readFixedLenInt()` function This function template reads an integer from a buffer without assuming its byte order. For example, this is needed when reading the magic number from a data buffer of unknown byte order. If needed, the user then has to manually swap byte order of that integer to get its native byte order Signed-off-by: Francis Deslauriers Change-Id: Ia94ee3a3ffc7caaa46a46defead3e23da0a4c2b2 Reviewed-on: https://review.lttng.org/c/babeltrace/+/8111 Reviewed-by: Philippe Proulx Reviewed-on: https://review.lttng.org/c/babeltrace/+/10841 CI-Build: Philippe Proulx Tested-by: jenkins --- diff --git a/src/cpp-common/read-fixed-len-int.hpp b/src/cpp-common/read-fixed-len-int.hpp index 27799e17..c0654f8b 100644 --- a/src/cpp-common/read-fixed-len-int.hpp +++ b/src/cpp-common/read-fixed-len-int.hpp @@ -17,18 +17,28 @@ namespace bt2_common { /* - * Reads a fixed-length little-endian integer into a value of integral + * Reads a fixed-length integer of unknown byte order into a value of integral * type `IntT` from the buffer `buf` and returns it. */ template -IntT readFixedLenIntLe(const std::uint8_t * const buf) +IntT readFixedLenInt(const std::uint8_t * const buf) { static_assert(std::is_integral::value, "`IntT` is an integral type."); IntT val; std::memcpy(&val, buf, sizeof(val)); - return bt2_common::littleEndianToNative(val); + return val; +} + +/* + * Reads a fixed-length little-endian integer into a value of integral + * type `IntT` from the buffer `buf` and returns it. + */ +template +IntT readFixedLenIntLe(const std::uint8_t * const buf) +{ + return bt2_common::littleEndianToNative(readFixedLenInt(buf)); } /* @@ -38,12 +48,7 @@ IntT readFixedLenIntLe(const std::uint8_t * const buf) template IntT readFixedLenIntBe(const std::uint8_t * const buf) { - static_assert(std::is_integral::value, "`IntT` is an integral type."); - - IntT val; - - std::memcpy(&val, buf, sizeof(val)); - return bt2_common::bigEndianToNative(val); + return bt2_common::bigEndianToNative(readFixedLenInt(buf)); } } /* namespace bt2_common */