Peternator7 / strum

A small rust library for adding custom derives to enums
https://crates.io/crates/strum
MIT License
1.77k stars 150 forks source link

Attribute to format field names #92

Open Luro02 opened 4 years ago

Luro02 commented 4 years ago

I would like to be able to do something like this

#[derive(Display)]
#[strum("series.{}", serialize_all = "snake_case")]
struct Series {
    Media
}

assert_eq!(Series::Media.to_string(), "series.media".to_string());

The attribute could also look like this

#[strum(format = "series.{}", serialize_all = "snake_case")]

The implementation would be relatively simple (I think?):

use syn::LitStr;

// parse this from the attribute:
let format_string = "series.{}".to_string();
// the serialized field name
let field_name = "media".to_string();

let lit_str = LitStr::new(&format_string.replace("{}", &field_name), Span::call_site());

quote {
    impl ::std::fmt::Display for Series {
        fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
            match &self {
                Self::Media => f.write_str(#lit_str),
            }
        }
    }
}
Peternator7 commented 4 years ago

That makes sense. As best we can, we should be able to round trip from strings so we also need the reverse direction string -> Enum.

Is this something you'd be interested in openin a PR for?

Luro02 commented 4 years ago

Is this something you'd be interested in openin a PR for?

Sorry I do not have the time right now :/

JimChenWYU commented 1 month ago
#[derive(Debug, Display)]
enum Series {
    #[strum(to_string = "series.media")]
    Media,
}
#[test]
fn case_assert() {
    assert_eq!("series.media", Series::Media.to_string());
}

Now can it solved?