protozero  1.6.2
Minimalistic protocol buffer decoder and encoder in C++.
byteswap.hpp
Go to the documentation of this file.
1 #ifndef PROTOZERO_BYTESWAP_HPP
2 #define PROTOZERO_BYTESWAP_HPP
3 
4 /*****************************************************************************
5 
6 protozero - Minimalistic protocol buffer decoder and encoder in C++.
7 
8 This file is from https://github.com/mapbox/protozero where you can find more
9 documentation.
10 
11 *****************************************************************************/
12 
19 #include <protozero/config.hpp>
20 
21 #include <cstdint>
22 
23 namespace protozero {
24 namespace detail {
25 
26 inline uint32_t byteswap_impl(uint32_t value) noexcept {
27 #ifdef PROTOZERO_USE_BUILTIN_BSWAP
28  return __builtin_bswap32(value);
29 #else
30  return ((value & 0xff000000) >> 24) |
31  ((value & 0x00ff0000) >> 8) |
32  ((value & 0x0000ff00) << 8) |
33  ((value & 0x000000ff) << 24);
34 #endif
35 }
36 
37 inline uint64_t byteswap_impl(uint64_t value) noexcept {
38 #ifdef PROTOZERO_USE_BUILTIN_BSWAP
39  return __builtin_bswap64(value);
40 #else
41  return ((value & 0xff00000000000000ULL) >> 56) |
42  ((value & 0x00ff000000000000ULL) >> 40) |
43  ((value & 0x0000ff0000000000ULL) >> 24) |
44  ((value & 0x000000ff00000000ULL) >> 8) |
45  ((value & 0x00000000ff000000ULL) << 8) |
46  ((value & 0x0000000000ff0000ULL) << 24) |
47  ((value & 0x000000000000ff00ULL) << 40) |
48  ((value & 0x00000000000000ffULL) << 56);
49 #endif
50 }
51 
52 inline void byteswap_inplace(uint32_t* ptr) noexcept {
53  *ptr = byteswap_impl(*ptr);
54 }
55 
56 inline void byteswap_inplace(uint64_t* ptr) noexcept {
57  *ptr = byteswap_impl(*ptr);
58 }
59 
60 inline void byteswap_inplace(int32_t* ptr) noexcept {
61  auto bptr = reinterpret_cast<uint32_t*>(ptr);
62  *bptr = byteswap_impl(*bptr);
63 }
64 
65 inline void byteswap_inplace(int64_t* ptr) noexcept {
66  auto bptr = reinterpret_cast<uint64_t*>(ptr);
67  *bptr = byteswap_impl(*bptr);
68 }
69 
70 inline void byteswap_inplace(float* ptr) noexcept {
71  auto bptr = reinterpret_cast<uint32_t*>(ptr);
72  *bptr = byteswap_impl(*bptr);
73 }
74 
75 inline void byteswap_inplace(double* ptr) noexcept {
76  auto bptr = reinterpret_cast<uint64_t*>(ptr);
77  *bptr = byteswap_impl(*bptr);
78 }
79 
80 } // end namespace detail
81 } // end namespace protozero
82 
83 #endif // PROTOZERO_BYTESWAP_HPP
Contains macro checks for different configurations.
All parts of the protozero header-only library are in this namespace.
Definition: byteswap.hpp:23