Commit | Line | Data |
---|---|---|
82a36560 PP |
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> | |
82a36560 PP |
11 | #include <cstring> |
12 | #include <type_traits> | |
13 | ||
14 | #include "cpp-common/endian.hpp" | |
15 | ||
16 | namespace bt2_common { | |
17 | ||
18 | /* | |
e0a3ddd4 | 19 | * Reads a fixed-length integer of unknown byte order into a value of integral |
82a36560 PP |
20 | * type `IntT` from the buffer `buf` and returns it. |
21 | */ | |
22 | template <typename IntT> | |
e0a3ddd4 | 23 | IntT readFixedLenInt(const std::uint8_t * const buf) |
82a36560 PP |
24 | { |
25 | static_assert(std::is_integral<IntT>::value, "`IntT` is an integral type."); | |
26 | ||
27 | IntT val; | |
28 | ||
29 | std::memcpy(&val, buf, sizeof(val)); | |
e0a3ddd4 FD |
30 | return val; |
31 | } | |
32 | ||
33 | /* | |
34 | * Reads a fixed-length little-endian integer into a value of integral | |
35 | * type `IntT` from the buffer `buf` and returns it. | |
36 | */ | |
37 | template <typename IntT> | |
38 | IntT readFixedLenIntLe(const std::uint8_t * const buf) | |
39 | { | |
40 | return bt2_common::littleEndianToNative(readFixedLenInt<IntT>(buf)); | |
82a36560 PP |
41 | } |
42 | ||
43 | /* | |
44 | * Reads a fixed-length big-endian integer into a value of integral | |
45 | * type `IntT` from the buffer `buf` and returns it. | |
46 | */ | |
47 | template <typename IntT> | |
48 | IntT readFixedLenIntBe(const std::uint8_t * const buf) | |
49 | { | |
e0a3ddd4 | 50 | return bt2_common::bigEndianToNative(readFixedLenInt<IntT>(buf)); |
82a36560 PP |
51 | } |
52 | ||
53 | } /* namespace bt2_common */ | |
54 | ||
55 | #endif /* BABELTRACE_CPP_COMMON_READ_FIXED_LEN_INT_HPP */ |