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 | /* | |
20 | * Reads a fixed-length little-endian integer into a value of integral | |
21 | * type `IntT` from the buffer `buf` and returns it. | |
22 | */ | |
23 | template <typename IntT> | |
24 | IntT readFixedLenIntLe(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 bt2_common::littleEndianToNative(val); | |
32 | } | |
33 | ||
34 | /* | |
35 | * Reads a fixed-length big-endian integer into a value of integral | |
36 | * type `IntT` from the buffer `buf` and returns it. | |
37 | */ | |
38 | template <typename IntT> | |
39 | IntT readFixedLenIntBe(const std::uint8_t * const buf) | |
40 | { | |
41 | static_assert(std::is_integral<IntT>::value, "`IntT` is an integral type."); | |
42 | ||
43 | IntT val; | |
44 | ||
45 | std::memcpy(&val, buf, sizeof(val)); | |
46 | return bt2_common::bigEndianToNative(val); | |
47 | } | |
48 | ||
49 | } /* namespace bt2_common */ | |
50 | ||
51 | #endif /* BABELTRACE_CPP_COMMON_READ_FIXED_LEN_INT_HPP */ |