sparrow 0.3.0
Loading...
Searching...
No Matches
bit.hpp
Go to the documentation of this file.
1// Copyright 2024 Man Group Operations Limited
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#pragma once
16
17#include <algorithm>
18#include <array>
19#include <bit>
20#include <concepts>
21
22namespace sparrow
23{
31 template <std::integral T>
32 [[nodiscard]] constexpr T byteswap(T value) noexcept
33 {
34 static_assert(std::has_unique_object_representations_v<T>, "T may not have padding bits");
35 auto value_representation = std::bit_cast<std::array<std::byte, sizeof(T)>>(value);
36 std::ranges::reverse(value_representation);
37 return std::bit_cast<T>(value_representation);
38 }
39
40 template <std::endian input_value_endianess>
41 [[nodiscard]] constexpr auto to_native_endian(std::integral auto value) noexcept
42 {
43 if constexpr (std::endian::native != input_value_endianess)
44 {
45 return byteswap(value);
46 }
47 else
48 {
49 return value;
50 }
51 }
52}
constexpr T byteswap(T value) noexcept
Reverses the bytes in the given integer value.
Definition bit.hpp:32
constexpr auto to_native_endian(std::integral auto value) noexcept
Definition bit.hpp:41