Skip to content
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

Allow to deserialize enums from their string representation #223

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/lib.rs
Expand Up @@ -61,6 +61,18 @@ macro_rules! lsp_enum {
}
}
}

impl std::convert::TryFrom<&String> for $typ {
type Error = &'static str;
fn try_from(value: &String) -> Result<Self, Self::Error> {
match value {
$(
_ if *value == format!("{:?}", Self::$name) => Ok(Self::$name),
)*
_ => Err("unknown enum variant"),
}
}
}
Comment on lines +65 to +75
Copy link
Member

@Marwes Marwes Nov 21, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
impl std::convert::TryFrom<&String> for $typ {
type Error = &'static str;
fn try_from(value: &String) -> Result<Self, Self::Error> {
match value {
$(
_ if *value == format!("{:?}", Self::$name) => Ok(Self::$name),
)*
_ => Err("unknown enum variant"),
}
}
}
impl std::convert::TryFrom<&str> for $typ {
type Error = &'static str;
fn try_from(value: &str) -> Result<Self, Self::Error> {
match value {
$(
stringify!($name) => Ok(Self::$name),
)*
_ => Err("unknown enum variant"),
}
}
}

No need to allocate for this

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, I was thinking to add a &'static str member to avoid the allocation.

Your suggestion is even more natural - though it requires FUNCTION as input instead of Function.
I don't have a strong opinion on which one is better. I guess we could keep symmetry with Debug while still only allocating once (converting value). Not sure what's better long-term.

}
}

Expand Down