| 1 | /* |
| 2 | * Copyright (c) 2022 Philippe Proulx <pproulx@efficios.com> |
| 3 | * |
| 4 | * SPDX-License-Identifier: MIT |
| 5 | */ |
| 6 | |
| 7 | #ifndef BABELTRACE_CPP_COMMON_BT2C_READ_FIXED_LEN_INT_HPP |
| 8 | #define BABELTRACE_CPP_COMMON_BT2C_READ_FIXED_LEN_INT_HPP |
| 9 | |
| 10 | #include <cstdint> |
| 11 | #include <cstring> |
| 12 | #include <type_traits> |
| 13 | |
| 14 | #include "endian.hpp" |
| 15 | |
| 16 | namespace bt2c { |
| 17 | |
| 18 | /* |
| 19 | * Reads a fixed-length integer of unknown byte order into a value of |
| 20 | * integral type `IntT` from the buffer `buf` and returns it. |
| 21 | */ |
| 22 | template <typename IntT> |
| 23 | IntT readFixedLenInt(const std::uint8_t * const buf) |
| 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)); |
| 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 littleEndianToNative(readFixedLenInt<IntT>(buf)); |
| 41 | } |
| 42 | |
| 43 | /* |
| 44 | * Reads a fixed-length big-endian integer into a value of integral type |
| 45 | * `IntT` from the buffer `buf` and returns it. |
| 46 | */ |
| 47 | template <typename IntT> |
| 48 | IntT readFixedLenIntBe(const std::uint8_t * const buf) |
| 49 | { |
| 50 | return bigEndianToNative(readFixedLenInt<IntT>(buf)); |
| 51 | } |
| 52 | |
| 53 | } /* namespace bt2c */ |
| 54 | |
| 55 | #endif /* BABELTRACE_CPP_COMMON_BT2C_READ_FIXED_LEN_INT_HPP */ |