MT Core (C++)
Core library for replacing C++ standard in project usage
Loading...
Searching...
No Matches
byte_order.hpp
Go to the documentation of this file.
1/*
2
3Copyright 2025 Matthew Tolman
4
5Licensed under the Apache License, Version 2.0 (the "License");
6you may not use this file except in compliance with the License.
7You may obtain a copy of the License at
8
9 http://www.apache.org/licenses/LICENSE-2.0
10
11Unless required by applicable law or agreed to in writing, software
12distributed under the License is distributed on an "AS IS" BASIS,
13WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14See the License for the specific language governing permissions and
15limitations under the License.
16
17*/
18
19#ifndef MTSTD_BYTE_ORDER_HPP
20#define MTSTD_BYTE_ORDER_HPP
21
22#include <bit>
23
28
30namespace mtcore {
32 namespace endian {
37 constexpr auto machine = std::endian::native;
42 constexpr auto opposite = std::endian::native == std::endian::little ? std::endian::big : std::endian::little;
43 } // namespace endian
44
49 constexpr u16 flip_endian_u16(const u16 bytes) { return bytes << 8 | ((bytes >> 8) & 0xFF); }
50
55 constexpr char16_t flip_endian_ch16(const char16_t ch) {
56 return static_cast<u16>(flip_endian_u16(static_cast<u16>(ch)));
57 }
58
63 constexpr u32 flip_endian_u32(const u32 bytes) {
64 return bytes << 24 | ((bytes << 8) & 0xFF0000) | ((bytes >> 8) & 0xFF00) | ((bytes >> 24) & 0xFF);
65 }
66
71 constexpr char32_t flip_endian_ch32(const char32_t ch) {
72 return static_cast<char32_t>(flip_endian_u32(static_cast<u32>(ch)));
73 }
74
79 template<typename T>
80 constexpr auto flip_endian(const T bytes) {
81 static_assert(std::same_as<u16, T> || std::same_as<char16_t, T> || std::same_as<u32, T> ||
82 std::same_as<char32_t, T>);
83 if constexpr (std::is_same_v<u16, T>) {
84 return flip_endian_u16(bytes);
85 }
86 else if constexpr (std::is_same_v<char16_t, T>) {
87 return flip_endian_ch16(bytes);
88 }
89 else if constexpr (std::is_same_v<u32, T>) {
90 return flip_endian_u32(bytes);
91 }
92 else {
93 return flip_endian_ch32(bytes);
94 }
95 }
96} // namespace mtcore
97
98#endif // MTSTD_BYTE_ORDER_HPP
constexpr char32_t flip_endian_ch32(const char32_t ch)
Flips the endianness of a char32.
constexpr char16_t flip_endian_ch16(const char16_t ch)
Flips the endianness of a char16.
constexpr u16 flip_endian_u16(const u16 bytes)
Flips the endianness of a u16.
constexpr auto opposite
endian that is opposite of machine (opposite of std::endian::native)
constexpr auto flip_endian(const T bytes)
Flips the endian of a u16, char16, u32, or char32.
constexpr u32 flip_endian_u32(const u32 bytes)
Flips the endianness of a u3.
constexpr auto machine
endian of machine (alias for std::endian::native)
uint16_t u16
Alias for 16-bit unsigned ints.
uint32_t u32
Alias for 32-bit unsigned ints.
Core library for C++ with Zig-related functionality.