protozero
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 <cstdint>
20 #include <cassert>
21 
22 namespace protozero {
23 
28 template <int N>
29 inline void byteswap(const char* /*data*/, char* /*result*/) {
30  static_assert(N == 1, "Can only swap 4 or 8 byte values");
31 }
32 
36 template <>
37 inline void byteswap<4>(const char* data, char* result) {
38 # if defined(__GNUC__) || defined(__clang__)
39  *reinterpret_cast<uint32_t*>(result) = __builtin_bswap32(*reinterpret_cast<const uint32_t*>(data));
40 # else
41  result[3] = data[0];
42  result[2] = data[1];
43  result[1] = data[2];
44  result[0] = data[3];
45 #endif
46 }
47 
51 template <>
52 inline void byteswap<8>(const char* data, char* result) {
53 # if defined(__GNUC__) || defined(__clang__)
54  *reinterpret_cast<uint64_t*>(result) = __builtin_bswap64(*reinterpret_cast<const uint64_t*>(data));
55 # else
56  result[7] = data[0];
57  result[6] = data[1];
58  result[5] = data[2];
59  result[4] = data[3];
60  result[3] = data[4];
61  result[2] = data[5];
62  result[1] = data[6];
63  result[0] = data[7];
64 #endif
65 }
66 
67 } // end namespace protozero
68 
69 #endif // PROTOZERO_BYTESWAP_HPP
void byteswap< 4 >(const char *data, char *result)
Definition: byteswap.hpp:37
void byteswap< 8 >(const char *data, char *result)
Definition: byteswap.hpp:52
void byteswap(const char *, char *)
Definition: byteswap.hpp:29
All parts of the protozero header-only library are in this namespace.
Definition: byteswap.hpp:22