mirror of
https://github.com/danog/strum.git
synced 2024-12-04 02:17:56 +01:00
e6a9bf08c4
The default attribute on a tuple like variant now causes the to_string and display format to use the value of the tuple rather than the name of the variant. E.g. Color::Green("lime").to_string() will equal "lime" not "Green" Fixes: how to round trip Display and EnumString with default="true" #86 BREAKING CHANGE This changes how Display and ToString cause the following to renders: ```rust #[strum(default)] Green(String) ``` To maintain the previous behavior (use the variant name): ```rust #[strum(default, to_string("Green"))] Green(String) ```
95 lines
2.1 KiB
Rust
95 lines
2.1 KiB
Rust
use strum::{Display, EnumString};
|
|
|
|
#[derive(Debug, Eq, PartialEq, EnumString, Display)]
|
|
enum Color {
|
|
#[strum(to_string = "RedRed")]
|
|
Red,
|
|
#[strum(serialize = "b", to_string = "blue")]
|
|
Blue { hue: usize },
|
|
#[strum(serialize = "y", serialize = "yellow")]
|
|
Yellow,
|
|
#[strum(default)]
|
|
Green(String),
|
|
}
|
|
|
|
#[test]
|
|
fn to_blue_string() {
|
|
assert_eq!(String::from("blue"), format!("{}", Color::Blue { hue: 0 }));
|
|
}
|
|
|
|
#[test]
|
|
fn test_formatters() {
|
|
assert_eq!(
|
|
String::from(" blue"),
|
|
format!("{:>6}", Color::Blue { hue: 0 })
|
|
);
|
|
assert_eq!(
|
|
String::from("blue "),
|
|
format!("{:<6}", Color::Blue { hue: 0 })
|
|
);
|
|
assert_eq!(
|
|
String::from(" blue "),
|
|
format!("{:^6}", Color::Blue { hue: 0 })
|
|
);
|
|
assert_eq!(String::from("bl"), format!("{:.2}", Color::Blue { hue: 0 }));
|
|
}
|
|
|
|
#[test]
|
|
fn to_yellow_string() {
|
|
assert_eq!(String::from("yellow"), format!("{}", Color::Yellow));
|
|
}
|
|
|
|
#[test]
|
|
fn to_red_string() {
|
|
assert_eq!(String::from("RedRed"), format!("{}", Color::Red));
|
|
}
|
|
|
|
#[test]
|
|
fn to_green_string() {
|
|
assert_eq!(
|
|
String::from("lime"),
|
|
format!("{}", Color::Green("lime".into()))
|
|
);
|
|
}
|
|
|
|
#[derive(Debug, Eq, PartialEq, EnumString, Display)]
|
|
enum ColorWithDefaultAndToString {
|
|
#[strum(default, to_string = "GreenGreen")]
|
|
Green(String),
|
|
}
|
|
|
|
#[test]
|
|
fn to_green_with_default_and_to_string() {
|
|
assert_eq!(
|
|
String::from("GreenGreen"),
|
|
format!("{}", ColorWithDefaultAndToString::Green("lime".into()))
|
|
);
|
|
}
|
|
|
|
#[derive(Display, Debug, Eq, PartialEq)]
|
|
#[strum(serialize_all = "snake_case")]
|
|
enum Brightness {
|
|
DarkBlack,
|
|
Dim {
|
|
glow: usize,
|
|
},
|
|
#[strum(serialize = "bright")]
|
|
BrightWhite,
|
|
}
|
|
|
|
#[test]
|
|
fn brightness_to_string() {
|
|
assert_eq!(
|
|
String::from("dark_black"),
|
|
Brightness::DarkBlack.to_string().as_ref()
|
|
);
|
|
assert_eq!(
|
|
String::from("dim"),
|
|
Brightness::Dim { glow: 0 }.to_string().as_ref()
|
|
);
|
|
assert_eq!(
|
|
String::from("bright"),
|
|
Brightness::BrightWhite.to_string().as_ref()
|
|
);
|
|
}
|