protozero  1.6.3
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 } // end namespace detail
53 
54 inline void byteswap_inplace(uint32_t* ptr) noexcept {
55  *ptr = detail::byteswap_impl(*ptr);
56 }
57 
58 inline void byteswap_inplace(uint64_t* ptr) noexcept {
59  *ptr = detail::byteswap_impl(*ptr);
60 }
61 
62 inline void byteswap_inplace(int32_t* ptr) noexcept {
63  auto bptr = reinterpret_cast<uint32_t*>(ptr);
64  *bptr = detail::byteswap_impl(*bptr);
65 }
66 
67 inline void byteswap_inplace(int64_t* ptr) noexcept {
68  auto bptr = reinterpret_cast<uint64_t*>(ptr);
69  *bptr = detail::byteswap_impl(*bptr);
70 }
71 
72 inline void byteswap_inplace(float* ptr) noexcept {
73  auto bptr = reinterpret_cast<uint32_t*>(ptr);
74  *bptr = detail::byteswap_impl(*bptr);
75 }
76 
77 inline void byteswap_inplace(double* ptr) noexcept {
78  auto bptr = reinterpret_cast<uint64_t*>(ptr);
79  *bptr = detail::byteswap_impl(*bptr);
80 }
81 
82 namespace detail {
83 
84  // Added for backwards compatibility with any code that might use this
85  // function (even if it shouldn't have). Will be removed in a later
86  // version of protozero.
87  using ::protozero::byteswap_inplace;
88 
89 } // end namespace detail
90 
91 } // end namespace protozero
92 
93 #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