cpp-common: add `readFixedLenInt()` function
[babeltrace.git] / src / cpp-common / read-fixed-len-int.hpp
CommitLineData
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
17namespace 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 */
23template <typename IntT>
e0a3ddd4 24IntT 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 */
38template <typename IntT>
39IntT 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 */
48template <typename IntT>
49IntT 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 */
This page took 0.030627 seconds and 4 git commands to generate.