2 * Copyright (c) 2022 Philippe Proulx <pproulx@efficios.com>
4 * SPDX-License-Identifier: MIT
7 #ifndef BABELTRACE_CPP_COMMON_READ_FIXED_LEN_INT_HPP
8 #define BABELTRACE_CPP_COMMON_READ_FIXED_LEN_INT_HPP
13 #include <type_traits>
15 #include "cpp-common/endian.hpp"
17 namespace bt2_common {
20 * Reads a fixed-length integer of unknown byte order into a value of integral
21 * type `IntT` from the buffer `buf` and returns it.
23 template <typename IntT>
24 IntT readFixedLenInt(const std::uint8_t * const buf)
26 static_assert(std::is_integral<IntT>::value, "`IntT` is an integral type.");
30 std::memcpy(&val, buf, sizeof(val));
35 * Reads a fixed-length little-endian integer into a value of integral
36 * type `IntT` from the buffer `buf` and returns it.
38 template <typename IntT>
39 IntT readFixedLenIntLe(const std::uint8_t * const buf)
41 return bt2_common::littleEndianToNative(readFixedLenInt<IntT>(buf));
45 * Reads a fixed-length big-endian integer into a value of integral
46 * type `IntT` from the buffer `buf` and returns it.
48 template <typename IntT>
49 IntT readFixedLenIntBe(const std::uint8_t * const buf)
51 return bt2_common::bigEndianToNative(readFixedLenInt<IntT>(buf));
54 } /* namespace bt2_common */
56 #endif /* BABELTRACE_CPP_COMMON_READ_FIXED_LEN_INT_HPP */