Skip to content

Use std::variant to implement pytree Key #6701

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Nov 12, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 14 additions & 28 deletions extension/pytree/pytree.h
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
#include <cstring>
#include <memory>
#include <string>
#include <variant>

// NB: This is a local, pytree FunctionRef and not from the ExecuTorch runtime.
#include <executorch/extension/pytree/function_ref.h>
Expand Down Expand Up @@ -55,51 +56,36 @@ using KeyInt = int32_t;
struct Key {
enum class Kind : uint8_t { None, Int, Str } kind_;

KeyInt as_int_ = {};
KeyStr as_str_ = {};
private:
std::variant<std::monostate, KeyInt, KeyStr> repr_;

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<Kind>(repr_.index());
}

const KeyInt& as_int() const {
pytree_assert(kind_ == Key::Kind::Int);
return as_int_;
KeyInt as_int() const {
return std::get<KeyInt>(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<KeyStr>(repr_);
}

operator const KeyStr&() const {
return as_str();
}

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 {
Expand Down
Loading