]> git-server-git.apps.pok.os.sepia.ceph.com Git - ceph.git/commitdiff
include/byteorder.h: rewrite swab() using boost::endian
authorKefu Chai <kchai@redhat.com>
Wed, 10 Mar 2021 05:05:32 +0000 (13:05 +0800)
committerKefu Chai <kchai@redhat.com>
Wed, 10 Mar 2021 08:56:44 +0000 (16:56 +0800)
boost::endian also uses the compiler intrinsics when available, so
no performance regressions. and the readability is improved.

Signed-off-by: Kefu Chai <kchai@redhat.com>
src/include/byteorder.h

index 4062c2d4c2e9301deb601c24080b2b33f55c7ceb..f934145cb7baa4e17c86f3345ab4c02a23073ff1 100644 (file)
@@ -2,67 +2,14 @@
 
 #pragma once
 
-#include <type_traits>
-#include "acconfig.h"
-#include "int_types.h"
-
+#include <boost/endian/conversion.hpp>
 
-#ifdef __GNUC__
-template<typename T>
-inline typename std::enable_if<sizeof(T) == sizeof(uint16_t), T>::type
-swab(T val) {
-  return __builtin_bswap16(val);
-}
-template<typename T>
-inline typename std::enable_if<sizeof(T) == sizeof(uint32_t), T>::type
-swab(T val) {
-  return __builtin_bswap32(val);
-}
-template<typename T>
-inline typename std::enable_if<sizeof(T) == sizeof(uint64_t), T>::type
-swab(T val) {
-  return __builtin_bswap64(val);
-}
-#else
-template<typename T>
-inline typename std::enable_if<sizeof(T) == sizeof(uint16_t), T>::type
-swab(T val) {
-  return (val >> 8) | (val << 8);
-}
-template<typename T>
-inline typename std::enable_if<sizeof(T) == sizeof(uint32_t), T>::type
-swab(T val) {
-  return (( val >> 24) |
-         ((val >> 8)  & 0xff00) |
-         ((val << 8)  & 0xff0000) | 
-         ((val << 24)));
-}
-template<typename T>
-inline typename std::enable_if<sizeof(T) == sizeof(uint64_t), T>::type
-swab(T val) {
-  return (( val >> 56) |
-         ((val >> 40) & 0xff00ull) |
-         ((val >> 24) & 0xff0000ull) |
-         ((val >> 8)  & 0xff000000ull) |
-         ((val << 8)  & 0xff00000000ull) |
-         ((val << 24) & 0xff0000000000ull) |
-         ((val << 40) & 0xff000000000000ull) |
-         ((val << 56)));
-}
-#endif
+#include "int_types.h"
 
-// mswab == maybe swab (if not LE)
-#ifdef CEPH_BIG_ENDIAN
-template<typename T>
-inline T mswab(T val) {
-  return swab(val);
-}
-#else
 template<typename T>
-inline T mswab(T val) {
-  return val;
+inline T swab(T val) {
+  return boost::endian::endian_reverse(val);
 }
-#endif
 
 template<typename T>
 struct ceph_le {
@@ -70,10 +17,10 @@ private:
   T v;
 public:
   ceph_le<T>& operator=(T nv) {
-    v = mswab(nv);
+    v = boost::endian::native_to_little(nv);
     return *this;
   }
-  operator T() const { return mswab(v); }
+  operator T() const { return boost::endian::little_to_native(v); }
   friend inline bool operator==(ceph_le a, ceph_le b) {
     return a.v == b.v;
   }