CppWAMP
C++11 client library for the WAMP protocol
endian.hpp
1 /*------------------------------------------------------------------------------
2  Copyright Butterfly Energy Systems 2014-2015, 2022.
3  Distributed under the Boost Software License, Version 1.0.
4  http://www.boost.org/LICENSE_1_0.txt
5 ------------------------------------------------------------------------------*/
6 
7 #ifndef CPPWAMP_ENDIAN_HPP
8 #define CPPWAMP_ENDIAN_HPP
9 
10 #include <cstdint>
11 
12 #if defined(__has_include) && __has_include(<bit>)
13 #include <bit>
14 #ifdef __cpp_lib_endian
15 #define CPPWAMP_HAS_STD_ENDIAN
16 #endif
17 #endif
18 
19 namespace wamp
20 {
21 
22 namespace internal
23 {
24 
25 namespace endian
26 {
27 
28 inline uint32_t flip(uint32_t n)
29 {
30  // This usually optimizes to a single byte swap instruction.
31  return ((n & 0xFF000000u) >> 24u) | ((n & 0x00FF0000u) >> 8u) |
32  ((n & 0x0000FF00u) << 8u) | ((n & 0x0000000FF) << 24u);
33 }
34 
35 constexpr bool nativeIsLittle()
36 {
37 #ifdef CPPWAMP_HAS_STD_ENDIAN
38  return (std::endian::native == std::endian::little);
39 #elif defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__)
40  return __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__;
41 #elif defined(_WIN32)
42  return true;
43 #elif defined(CPPWAMP_ASSUME_LITTLE_ENDIAN)
44  return true;
45 #elif defined(CPPWAMP_ASSUME_BIG_ENDIAN)
46  return false;
47 #else
48 #warning Cannot detect endianness; assuming little endian
49 #warning Please define either CPPWAMP_ASSUME_LITTLE_ENDIAN or CPPWAMP_ASSUME_BIG_ENDIAN
50  return little_endian;
51 #endif
52 }
53 
54 inline uint32_t nativeToBig32(uint32_t native)
55 {
56  return nativeIsLittle() ? flip(native) : native;
57 }
58 
59 inline uint32_t bigToNative32(uint32_t big)
60 {
61  return nativeIsLittle() ? flip(big) : big;
62 }
63 
64 
65 } // namespace endian
66 
67 } // namespace internal
68 
69 } // namespace wamp
70 
71 
72 #endif // CPPWAMP_ENDIAN_HPP
wamp
Definition: anyhandler.hpp:36