cpp-common: add `readFixedLenInt()` function
authorFrancis Deslauriers <francis.deslauriers@efficios.com>
Wed, 25 May 2022 15:20:53 +0000 (11:20 -0400)
committerPhilippe Proulx <eeppeliteloop@gmail.com>
Mon, 11 Sep 2023 15:24:02 +0000 (11:24 -0400)
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 <francis.deslauriers@efficios.com>
Change-Id: Ia94ee3a3ffc7caaa46a46defead3e23da0a4c2b2
Reviewed-on: https://review.lttng.org/c/babeltrace/+/8111
Reviewed-by: Philippe Proulx <eeppeliteloop@gmail.com>
Reviewed-on: https://review.lttng.org/c/babeltrace/+/10841
CI-Build: Philippe Proulx <eeppeliteloop@gmail.com>
Tested-by: jenkins <jenkins@lttng.org>
src/cpp-common/read-fixed-len-int.hpp

index 27799e17af7b53f7a6264854d31781a5fb1e70f8..c0654f8b621d25ec932c3d8d4aeffef3c8450891 100644 (file)
 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 <typename IntT>
-IntT readFixedLenIntLe(const std::uint8_t * const buf)
+IntT readFixedLenInt(const std::uint8_t * const buf)
 {
     static_assert(std::is_integral<IntT>::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 <typename IntT>
+IntT readFixedLenIntLe(const std::uint8_t * const buf)
+{
+    return bt2_common::littleEndianToNative(readFixedLenInt<IntT>(buf));
 }
 
 /*
@@ -38,12 +48,7 @@ IntT readFixedLenIntLe(const std::uint8_t * const buf)
 template <typename IntT>
 IntT readFixedLenIntBe(const std::uint8_t * const buf)
 {
-    static_assert(std::is_integral<IntT>::value, "`IntT` is an integral type.");
-
-    IntT val;
-
-    std::memcpy(&val, buf, sizeof(val));
-    return bt2_common::bigEndianToNative(val);
+    return bt2_common::bigEndianToNative(readFixedLenInt<IntT>(buf));
 }
 
 } /* namespace bt2_common */
This page took 0.025847 seconds and 4 git commands to generate.