|
15 | 15 | #include <cstring> |
16 | 16 | #include <memory> |
17 | 17 | #include <string> |
| 18 | +#include <variant> |
18 | 19 |
|
19 | 20 | // NB: This is a local, pytree FunctionRef and not from the ExecuTorch runtime. |
20 | 21 | #include <executorch/extension/pytree/function_ref.h> |
@@ -54,52 +55,36 @@ using KeyInt = int32_t; |
54 | 55 |
|
55 | 56 | struct Key { |
56 | 57 | enum class Kind : uint8_t { None, Int, Str } kind_; |
| 58 | + private: |
| 59 | + std::variant<std::monostate, KeyInt, KeyStr> repr_; |
57 | 60 |
|
58 | | - KeyInt as_int_ = {}; |
59 | | - KeyStr as_str_ = {}; |
60 | | - |
61 | | - Key() : kind_(Kind::None) {} |
62 | | - /*implicit*/ Key(KeyInt key) : kind_(Kind::Int), as_int_(std::move(key)) {} |
63 | | - /*implicit*/ Key(KeyStr key) : kind_(Kind::Str), as_str_(std::move(key)) {} |
| 61 | + public: |
| 62 | + Key() {} |
| 63 | + /*implicit*/ Key(KeyInt key) : repr_(key) {} |
| 64 | + /*implicit*/ Key(KeyStr key) : repr_(std::move(key)) {} |
64 | 65 |
|
65 | | - const Kind& kind() const { |
66 | | - return kind_; |
| 66 | + Kind kind() const { |
| 67 | + return static_cast<Kind>(repr_.index()); |
67 | 68 | } |
68 | 69 |
|
69 | | - const KeyInt& as_int() const { |
70 | | - pytree_assert(kind_ == Key::Kind::Int); |
71 | | - return as_int_; |
| 70 | + KeyInt as_int() const { |
| 71 | + return std::get<KeyInt>(repr_); |
72 | 72 | } |
73 | 73 |
|
74 | | - operator const KeyInt&() const { |
| 74 | + operator KeyInt() const { |
75 | 75 | return as_int(); |
76 | 76 | } |
77 | 77 |
|
78 | 78 | const KeyStr& as_str() const { |
79 | | - pytree_assert(kind_ == Key::Kind::Str); |
80 | | - return as_str_; |
| 79 | + return std::get<KeyStr>(repr_); |
81 | 80 | } |
82 | 81 |
|
83 | 82 | operator const KeyStr&() const { |
84 | 83 | return as_str(); |
85 | 84 | } |
86 | 85 |
|
87 | 86 | bool operator==(const Key& rhs) const { |
88 | | - if (kind_ != rhs.kind_) { |
89 | | - return false; |
90 | | - } |
91 | | - switch (kind_) { |
92 | | - case Kind::Str: { |
93 | | - return as_str_ == rhs.as_str_; |
94 | | - } |
95 | | - case Kind::Int: { |
96 | | - return as_int_ == rhs.as_int_; |
97 | | - } |
98 | | - case Kind::None: { |
99 | | - return true; |
100 | | - } |
101 | | - } |
102 | | - pytree_unreachable(); |
| 87 | + return repr_ == rhs.repr_; |
103 | 88 | } |
104 | 89 |
|
105 | 90 | bool operator!=(const Key& rhs) const { |
|
0 commit comments