strum icon indicating copy to clipboard operation
strum copied to clipboard

Iterate over all serialize properties of a variant as Strings

Open SeanMcLoughlin opened this issue 4 years ago • 2 comments

Is there any way to iterate over all serialize properties of a variant? I can't seem to find anything about doing this in the documentation.

I am making a parser where I need to treat multiple different characters as whitespace.

#[derive(Debug, Display, Eq, PartialEq, Clone, EnumString, EnumIter, AsStaticStr)]
enum TokenType {
    // Others...
    #[strum(serialize = " ", serialize = "\r", serialize = "\t")]
    Whitespace,
    // Others...
}

I want to get a list of every variant's serialize strings. Currently, I'm only able to get one of the properties.

fn match_whitespace() {
    // I need ALL serialize properties as strings for 
    // EVERY variant added to to this list.
    // 
    // Currently, this just uses `.as_static()`, which seems to 
    // follow the rules of `to_string()` and return the longest of 
    // the serialize property's string. 
    let list_of_token_strings = TokenType::iter()
        .map(|tok| tok.as_static())
        .collect::<Vec<&'static str>>();
}

I'd like to be able to iterate over the serialize properties within tok.

SeanMcLoughlin avatar Dec 29 '20 05:12 SeanMcLoughlin

Hey @SeanMcLoughlin, this isn't supported right now, but it's certainly within the scope of strum. If you're interested in adding it, I'd happily accept a PR; otherwise, I'll add it to the backlog and work on it when I find some time.

Peternator7 avatar Jan 19 '21 18:01 Peternator7

Hey @SeanMcLoughlin , I think I found a workaround for the moment. 3869b6fa907b1dae96f224ce12e91d3531c5621b changed the variance of get_serializations to 'static which made possible the following code:

#[derive(Debug, Eq, PartialEq, Clone, EnumString, EnumIter, AsStaticStr, EnumMessage)]
enum TokenType {
    // Others...
    #[strum(serialize = " ", serialize = "\r", serialize = "\t")]
    Whitespace,
    // Others...
}

fn main() {
    let list_of_token_strings = TokenType::iter()
        .map(|tok| tok.get_serializations().to_vec())
        .flatten()
        .collect::<Vec<&'static str>>();

    assert_eq!(list_of_token_strings, vec![" ", "\r", "\t"])
}

What do you think @Peternator7 ?

lesavonfou avatar May 29 '21 11:05 lesavonfou