c0654f8b621d25ec932c3d8d4aeffef3c8450891
[babeltrace.git] / src / cpp-common / read-fixed-len-int.hpp
1 /*
2 * Copyright (c) 2022 Philippe Proulx <pproulx@efficios.com>
3 *
4 * SPDX-License-Identifier: MIT
5 */
6
7 #ifndef BABELTRACE_CPP_COMMON_READ_FIXED_LEN_INT_HPP
8 #define BABELTRACE_CPP_COMMON_READ_FIXED_LEN_INT_HPP
9
10 #include <cstdint>
11 #include <cstdlib>
12 #include <cstring>
13 #include <type_traits>
14
15 #include "cpp-common/endian.hpp"
16
17 namespace bt2_common {
18
19 /*
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.
22 */
23 template <typename IntT>
24 IntT readFixedLenInt(const std::uint8_t * const buf)
25 {
26 static_assert(std::is_integral<IntT>::value, "`IntT` is an integral type.");
27
28 IntT val;
29
30 std::memcpy(&val, buf, sizeof(val));
31 return val;
32 }
33
34 /*
35 * Reads a fixed-length little-endian integer into a value of integral
36 * type `IntT` from the buffer `buf` and returns it.
37 */
38 template <typename IntT>
39 IntT readFixedLenIntLe(const std::uint8_t * const buf)
40 {
41 return bt2_common::littleEndianToNative(readFixedLenInt<IntT>(buf));
42 }
43
44 /*
45 * Reads a fixed-length big-endian integer into a value of integral
46 * type `IntT` from the buffer `buf` and returns it.
47 */
48 template <typename IntT>
49 IntT readFixedLenIntBe(const std::uint8_t * const buf)
50 {
51 return bt2_common::bigEndianToNative(readFixedLenInt<IntT>(buf));
52 }
53
54 } /* namespace bt2_common */
55
56 #endif /* BABELTRACE_CPP_COMMON_READ_FIXED_LEN_INT_HPP */
This page took 0.030085 seconds and 3 git commands to generate.