Skip to content

Commit

Permalink
Also convert case when deriving Display.
Browse files Browse the repository at this point in the history
  • Loading branch information
azriel91 committed Sep 20, 2018
1 parent 2e6b4a5 commit 1e8b948
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
9 changes: 7 additions & 2 deletions strum_macros/src/display.rs
@@ -1,7 +1,8 @@
use proc_macro2::TokenStream;
use syn;

use helpers::{extract_attrs, extract_meta, is_disabled, unique_attr};
use case_style::CaseStyle;
use helpers::{convert_case, extract_attrs, extract_meta, is_disabled, unique_attr};

pub fn display_inner(ast: &syn::DeriveInput) -> TokenStream {
let name = &ast.ident;
Expand All @@ -11,6 +12,10 @@ pub fn display_inner(ast: &syn::DeriveInput) -> TokenStream {
_ => panic!("Display only works on Enums"),
};

let type_meta = extract_meta(&ast.attrs);
let case_style = unique_attr(&type_meta, "strum", "serialize_all")
.map(|style| CaseStyle::from(style.as_ref()));

let mut arms = Vec::new();
for variant in variants {
use syn::Fields::*;
Expand All @@ -31,7 +36,7 @@ pub fn display_inner(ast: &syn::DeriveInput) -> TokenStream {
if let Some(n) = attrs.pop() {
n
} else {
ident.to_string()
convert_case(ident, case_style)
}
};

Expand Down
27 changes: 27 additions & 0 deletions strum_tests/tests/display.rs
Expand Up @@ -28,3 +28,30 @@ fn to_yellow_string() {
fn to_red_string() {
assert_eq!(String::from("RedRed"), format!("{}", Color::Red));
}

#[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()
);
}

0 comments on commit 1e8b948

Please sign in to comment.