]> git.apps.os.sepia.ceph.com Git - ceph.git/commitdiff
denc: support enum with underlying type 18701/head
authorKefu Chai <kchai@redhat.com>
Fri, 3 Nov 2017 08:10:07 +0000 (16:10 +0800)
committerKefu Chai <kchai@redhat.com>
Fri, 3 Nov 2017 08:30:59 +0000 (16:30 +0800)
Signed-off-by: Kefu Chai <kchai@redhat.com>
src/include/denc.h
src/test/encoding.cc

index 823da640860b7ca5f09ea88b3f47708c7670203c..9dc1b7b5f4c6a321b508a479876c4e2702748d0b 100644 (file)
@@ -231,6 +231,13 @@ namespace _denc {
     std::true_type,
     is_any_of<T, Tail...>>::type
   {};
+  template<typename T, typename=void> struct underlying_type {
+    using type = T;
+  };
+  template<typename T> struct underlying_type<
+    T, typename std::enable_if<std::is_enum<T>::value>::type> {
+    using type = typename std::underlying_type<T>::type;
+  };
 }
 
 
@@ -238,7 +245,8 @@ template<typename T>
 struct denc_traits<
   T,
   typename std::enable_if<
-    _denc::is_any_of<T, ceph_le64, ceph_le32, ceph_le16, uint8_t
+    _denc::is_any_of<typename _denc::underlying_type<T>::type,
+                    ceph_le64, ceph_le32, ceph_le16, uint8_t
 #ifndef _CHAR_IS_SIGNED
                     , int8_t
 #endif
index af3346e1a0916dbd27fc62430fe7238d35bcf50c..21e31d4fab9f423804b2502e1cfeefdd1a991fc7 100644 (file)
@@ -264,6 +264,23 @@ void encode<ceph_le64, denc_traits<ceph_le64>>(const ceph_le64&,
   ASSERT_TRUE(false);
 }
 
+namespace {
+  // search `underlying_type` in denc.h for supported underlying types
+  enum class Colour : int8_t { R,G,B };
+  ostream& operator<<(ostream& os, Colour c) {
+    switch (c) {
+    case Colour::R:
+      return os << "Colour::R";
+    case Colour::G:
+      return os << "Colour::G";
+    case Colour::B:
+      return os << "Colour::B";
+    default:
+      return os << "Colour::???";
+    }
+  }
+}
+
 TEST(EncodingRoundTrip, Integers) {
   // int types
   {
@@ -288,6 +305,16 @@ TEST(EncodingRoundTrip, Integers) {
     i = 42;
     test_encode_and_decode(i);
   }
+  // enum
+  {
+    test_encode_and_decode(Colour::R);
+    // this should not build, as the size of unsigned is not the same on
+    // different archs, that's why denc_traits<> intentionally leaves
+    // `int` and `unsigned int` out of supported types.
+    //
+    // enum E { R, G, B };
+    // test_encode_and_decode(R);
+  }
 }
 
 const char* expected_what[] = {