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> | |
11 | #include <cstdlib> | |
12 | #include <cstring> | |
13 | #include <type_traits> | |
14 | ||
15 | #include "cpp-common/endian.hpp" | |
16 | ||
17 | namespace bt2_common { | |
18 | ||
19 | /* | |
e0a3ddd4 | 20 | * Reads a fixed-length integer of unknown byte order into a value of integral |
82a36560 PP |
21 | * type `IntT` from the buffer `buf` and returns it. |
22 | */ | |
23 | template <typename IntT> | |
e0a3ddd4 | 24 | IntT readFixedLenInt(const std::uint8_t * const buf) |
82a36560 PP |
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)); | |
e0a3ddd4 FD |
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)); | |
82a36560 PP |
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 | { | |
e0a3ddd4 | 51 | return bt2_common::bigEndianToNative(readFixedLenInt<IntT>(buf)); |
82a36560 PP |
52 | } |
53 | ||
54 | } /* namespace bt2_common */ | |
55 | ||
56 | #endif /* BABELTRACE_CPP_COMMON_READ_FIXED_LEN_INT_HPP */ |