Bladeren bron

refactor: cleanup and alignment guarantees

Sam Jaffe 1 maand geleden
bovenliggende
commit
0717490adf
2 gewijzigde bestanden met toevoegingen van 13 en 11 verwijderingen
  1. 13 1
      include/jvalidate/constraint.h
  2. 0 10
      include/jvalidate/detail/iostream.h

+ 13 - 1
include/jvalidate/constraint.h

@@ -36,6 +36,7 @@
 
 #define DECLARE_TYPE_ENUM(X) X,
 #define SIZEOF_STRUCT(X) sizeof(X),
+#define ALIGNOF_STRUCT(X) alignof(X),
 #define SWITCH_DELETE(X)                                                                           \
   case Type::X:                                                                                    \
     reinterpret_cast<X const *>(data_.data())->~X();                                               \
@@ -51,6 +52,10 @@
 namespace jvalidate::constraint {
 
 class Constraint {
+public:
+  static constexpr size_t UNION_WIDTH = std::max({CONSTRAINT_IMPLEMENTATION_LIST(SIZEOF_STRUCT)});
+  static constexpr size_t UNION_ALIGN = std::max({CONSTRAINT_IMPLEMENTATION_LIST(ALIGNOF_STRUCT)});
+
 public:
   CONSTRAINT_IMPLEMENTATION_LIST(IMPLICIT_CONSTRUCTOR)
   Constraint(Constraint const &) = delete;
@@ -88,7 +93,7 @@ private:
   enum class Type : uint8_t { None, CONSTRAINT_IMPLEMENTATION_LIST(DECLARE_TYPE_ENUM) };
 
   Type type_ = Type::None;
-  std::array<std::byte, std::max({CONSTRAINT_IMPLEMENTATION_LIST(SIZEOF_STRUCT)})> data_;
+  alignas(UNION_ALIGN) std::array<std::byte, UNION_WIDTH> data_;
 };
 }
 
@@ -1397,4 +1402,11 @@ public:
   }
 };
 }
+
+#undef DECLARE_TYPE_ENUM
+#undef SIZEOF_STRUCT
+#undef ALIGNOF_STRUCT
+#undef SWITCH_DELETE
+#undef SWITCH_VISIT
+#undef IMPLICIT_CONSTRUCTOR
 // NOLINTEND(readability-identifier-naming)

+ 0 - 10
include/jvalidate/detail/iostream.h

@@ -52,16 +52,6 @@ inline std::ostream & operator<<(std::ostream & os, Version version) {
 }
 
 namespace jvalidate {
-inline std::ostream & operator<<(std::ostream & os, Status stat) {
-  if (stat == Status::Accept) {
-    return os << "Accept";
-  }
-  if (stat == Status::Reject) {
-    return os << "Reject";
-  }
-  return os << "Noop";
-}
-
 template <typename T>
 inline std::ostream & operator<<(std::ostream & os, std::set<T> const & data) {
   if (data.size() == 1) {