From c5f21bc08a754fc74fc3af35bbefc2ce731f0093 Mon Sep 17 00:00:00 2001 From: Scott Wolchok Date: Wed, 6 Nov 2024 16:58:47 -0800 Subject: [PATCH 1/2] Use std::variant to implement pytree Key Key was a struct that should've been a union; std::variant makes using a union much easier. Differential Revision: [D65575184](https://our.internmc.facebook.com/intern/diff/D65575184/) [ghstack-poisoned] --- extension/pytree/pytree.h | 43 +++++++++++++-------------------------- 1 file changed, 14 insertions(+), 29 deletions(-) diff --git a/extension/pytree/pytree.h b/extension/pytree/pytree.h index 78e2305fe3e..8141a104c04 100644 --- a/extension/pytree/pytree.h +++ b/extension/pytree/pytree.h @@ -15,6 +15,7 @@ #include #include #include +#include // NB: This is a local, pytree FunctionRef and not from the ExecuTorch runtime. #include @@ -54,30 +55,28 @@ using KeyInt = int32_t; struct Key { enum class Kind : uint8_t { None, Int, Str } kind_; + private: + std::variant repr_; - KeyInt as_int_ = {}; - KeyStr as_str_ = {}; - - Key() : kind_(Kind::None) {} - /*implicit*/ Key(KeyInt key) : kind_(Kind::Int), as_int_(std::move(key)) {} - /*implicit*/ Key(KeyStr key) : kind_(Kind::Str), as_str_(std::move(key)) {} + public: + Key() {} + /*implicit*/ Key(KeyInt key) : repr_(key) {} + /*implicit*/ Key(KeyStr key) : repr_(std::move(key)) {} - const Kind& kind() const { - return kind_; + Kind kind() const { + return static_cast(repr_.index()); } - const KeyInt& as_int() const { - pytree_assert(kind_ == Key::Kind::Int); - return as_int_; + KeyInt as_int() const { + return std::get(repr_); } - operator const KeyInt&() const { + operator KeyInt() const { return as_int(); } const KeyStr& as_str() const { - pytree_assert(kind_ == Key::Kind::Str); - return as_str_; + return std::get(repr_); } operator const KeyStr&() const { @@ -85,21 +84,7 @@ struct Key { } bool operator==(const Key& rhs) const { - if (kind_ != rhs.kind_) { - return false; - } - switch (kind_) { - case Kind::Str: { - return as_str_ == rhs.as_str_; - } - case Kind::Int: { - return as_int_ == rhs.as_int_; - } - case Kind::None: { - return true; - } - } - pytree_unreachable(); + return repr_ == rhs.repr_; } bool operator!=(const Key& rhs) const { From ae9b0182ba66b52cdc45dd43c9f290c171ba3118 Mon Sep 17 00:00:00 2001 From: Scott Wolchok Date: Thu, 7 Nov 2024 06:50:45 -0800 Subject: [PATCH 2/2] Update on "Use std::variant to implement pytree Key" Key was a struct that should've been a union; std::variant makes using a union much easier. Differential Revision: [D65575184](https://our.internmc.facebook.com/intern/diff/D65575184/) [ghstack-poisoned] --- extension/pytree/pytree.h | 1 + 1 file changed, 1 insertion(+) diff --git a/extension/pytree/pytree.h b/extension/pytree/pytree.h index 8141a104c04..9c7202fb865 100644 --- a/extension/pytree/pytree.h +++ b/extension/pytree/pytree.h @@ -55,6 +55,7 @@ using KeyInt = int32_t; struct Key { enum class Kind : uint8_t { None, Int, Str } kind_; + private: std::variant repr_;