Stroika Library 3.0d25
 
Loading...
Searching...
No Matches
Endian.inl
1/*
2 * Copyright(c) Sophist Solutions, Inc. 1990-2026. All rights reserved
3 */
4#include <array>
5#include <bit>
6#include <cstdint>
7
9
11
12 /*
13 ********************************************************************************
14 ****************************** Common::GetEndianness ***************************
15 ********************************************************************************
16 */
17 inline constexpr Endian GetEndianness ()
18 {
19 // The byte order of a known value. bit_cast may look at an object's bytes in a constant expression; reading a
20 // union member other than the one last written may not (in any C++ version). std::endian alone cannot tell the
21 // two word-swapped orders apart.
22 constexpr auto kBytes_ = bit_cast<array<uint8_t, 4>> (uint32_t{0x01020304});
23 return kBytes_[0] == 4 ? Endian::eLittleByte
24 : kBytes_[0] == 1 ? Endian::eBigByte
25 : kBytes_[0] == 2 ? Endian::eLittleWord
26 : Endian::eBigWord;
27 }
28
29 /*
30 ********************************************************************************
31 **************************** Common::EndianConverter ***************************
32 ********************************************************************************
33 */
34 template <integral T>
35 constexpr inline T EndianConverter (T value, Endian from, Endian to)
36 {
37 if (from == to) {
38 return value;
39 }
40 Require (from == Endian::eBig or from == Endian::eLittle); // just cuz that's all that's implemented
41 Require (to == Endian::eBig or to == Endian::eLittle); // ""
42 // @todo re-implement some cases using https://en.cppreference.com/w/cpp/numeric/byteswap
43 // Require ((from == Endian::eBig or from == Endian::eLittle) and (to == Endian::eBig or to == Endian::eLittle));
44 // return std::byteswap (value) ;; double check this is right for all integral sizes... and use my stdcompat code for this
45 if constexpr (sizeof (T) == 1) {
46 return value;
47 }
48 if constexpr (sizeof (T) == 2) {
49 // since we only support big endian and little endian and from != to - swap is easy
50 return ((value & 0xFF) << 8) | ((value >> 8) & 0xFF);
51 }
52 if constexpr (sizeof (T) == 4) {
53 // since we only support big endian and little endian and from != to - I THINK This is right...
54 return ((value & 0xFF) << 24) | ((value & 0xFF00) << 8) | ((value >> 8) & 0xFF00) | ((value >> 24) & 0xFF);
55 }
57 return value;
58 }
59
60}
#define AssertNotImplemented()
Definition Assertions.h:404
Endian
in principle complicated question of correspondence between bit and byte and word numbering,...
Definition Endian.h:30
constexpr Endian GetEndianness()
returns native (std::endian::native) Endianness flag. Can be complicated (mixed, etc)....
Definition Endian.inl:17
constexpr T EndianConverter(T value, Endian from, Endian to)
Definition Endian.inl:35