Toolbox snapshot
The Reactive C++ Toolbox
Loading...
Searching...
No Matches
Endian.hpp
Go to the documentation of this file.
1// The Reactive C++ Toolbox.
2// Copyright (C) 2013-2019 Swirly Cloud Limited
3// Copyright (C) 2022 Reactive Markets Limited
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17#ifndef TOOLBOX_NET_ENDIAN_HPP
18#define TOOLBOX_NET_ENDIAN_HPP
19
20#include <bit>
21#include <concepts>
22#include <cstdint>
23
24namespace toolbox {
25inline namespace net {
26
27template <typename ValueT>
28 requires std::integral<ValueT>
29constexpr ValueT ntoh(ValueT n) noexcept
30{
31 if constexpr (std::endian::native == std::endian::little) {
32 return std::byteswap(n);
33 } else {
34 return n;
35 }
36}
37
38template <typename ValueT>
39 requires std::integral<ValueT>
40constexpr ValueT hton(ValueT n) noexcept
41{
42 if constexpr (std::endian::native == std::endian::little) {
43 return std::byteswap(n);
44 } else {
45 return n;
46 }
47}
48
49template <typename ValueT>
50 requires std::integral<ValueT>
51constexpr ValueT ltoh(ValueT n) noexcept
52{
53 if constexpr (std::endian::native == std::endian::little) {
54 return n;
55 } else {
56 return std::byteswap(n);
57 }
58}
59
60template <typename ValueT>
61 requires std::integral<ValueT>
62constexpr ValueT htol(ValueT n) noexcept
63{
64 if constexpr (std::endian::native == std::endian::little) {
65 return n;
66 } else {
67 return std::byteswap(n);
68 }
69}
70// Prevent corner case if mixed platform would use htol of big endian
71static_assert(std::endian::native == std::endian::little || std::endian::native == std::endian::big,
72 "Mixed endianness platforms are not supported");
73
74} // namespace net
75} // namespace toolbox
76
77#endif // TOOLBOX_NET_ENDIAN_HPP
constexpr ValueT hton(ValueT n) noexcept
Definition Endian.hpp:40
constexpr ValueT ltoh(ValueT n) noexcept
Definition Endian.hpp:51
constexpr ValueT ntoh(ValueT n) noexcept
Definition Endian.hpp:29
constexpr ValueT htol(ValueT n) noexcept
Definition Endian.hpp:62
constexpr auto bind() noexcept
Definition Slot.hpp:97