Fix some bugs when testing opensds ansible
[stor4nfv.git] / src / ceph / src / include / byteorder.h
1 // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
2
3 #pragma once
4
5 #include <type_traits>
6 #include "acconfig.h"
7 #include "int_types.h"
8
9
10 #ifdef __GNUC__
11 template<typename T>
12 inline typename std::enable_if<sizeof(T) == sizeof(uint16_t), T>::type
13 swab(T val) {
14   return __builtin_bswap16(val);
15 }
16 template<typename T>
17 inline typename std::enable_if<sizeof(T) == sizeof(uint32_t), T>::type
18 swab(T val) {
19   return __builtin_bswap32(val);
20 }
21 template<typename T>
22 inline typename std::enable_if<sizeof(T) == sizeof(uint64_t), T>::type
23 swab(T val) {
24   return __builtin_bswap64(val);
25 }
26 #else
27 template<typename T>
28 inline typename std::enable_if<sizeof(T) == sizeof(uint16_t), T>::type
29 swab(T val) {
30   return (val >> 8) | (val << 8);
31 }
32 template<typename T>
33 inline typename std::enable_if<sizeof(T) == sizeof(uint32_t), T>::type
34 swab(T val) {
35   return (( val >> 24) |
36           ((val >> 8)  & 0xff00) |
37           ((val << 8)  & 0xff0000) | 
38           ((val << 24)));
39 }
40 template<typename T>
41 inline typename std::enable_if<sizeof(T) == sizeof(uint64_t), T>::type
42 swab(T val) {
43   return (( val >> 56) |
44           ((val >> 40) & 0xff00ull) |
45           ((val >> 24) & 0xff0000ull) |
46           ((val >> 8)  & 0xff000000ull) |
47           ((val << 8)  & 0xff00000000ull) |
48           ((val << 24) & 0xff0000000000ull) |
49           ((val << 40) & 0xff000000000000ull) |
50           ((val << 56)));
51 }
52 #endif
53
54 // mswab == maybe swab (if not LE)
55 #ifdef CEPH_BIG_ENDIAN
56 template<typename T>
57 inline T mswab(T val) {
58   return swab(val);
59 }
60 #else
61 template<typename T>
62 inline T mswab(T val) {
63   return val;
64 }
65 #endif
66
67 template<typename T>
68 struct ceph_le {
69   T v;
70   ceph_le<T>& operator=(T nv) {
71     v = mswab(nv);
72     return *this;
73   }
74   operator T() const { return mswab(v); }
75 } __attribute__ ((packed));
76
77 template<typename T>
78 inline bool operator==(ceph_le<T> a, ceph_le<T> b) {
79   return a.v == b.v;
80 }
81
82 using ceph_le64 = ceph_le<__u64>;
83 using ceph_le32 = ceph_le<__u32>;
84 using ceph_le16 = ceph_le<__u16>;
85
86 inline __u64 init_le64(__u64 x) {
87   return mswab<__u64>(x);
88 }
89 inline __u32 init_le32(__u32 x) {
90   return mswab<__u32>(x);
91 }
92 inline __u16 init_le16(__u16 x) {
93   return mswab<__u16>(x);
94 }
95
96   /*
97 #define cpu_to_le64(x) (x)
98 #define cpu_to_le32(x) (x)
99 #define cpu_to_le16(x) (x)
100   */
101 #define le64_to_cpu(x) ((uint64_t)x)
102 #define le32_to_cpu(x) ((__u32)x)
103 #define le16_to_cpu(x) ((__u16)x)