tabled_derive/
casing_style.rs

1use crate::error::Error;
2
3/// Defines the casing for the attributes long representation.
4#[derive(Copy, Clone, Debug, PartialEq, Eq)]
5pub enum CasingStyle {
6    /// Indicate word boundaries with uppercase letter, excluding the first word.
7    Camel,
8    /// Keep all letters lowercase and indicate word boundaries with hyphens.
9    Kebab,
10    /// Indicate word boundaries with uppercase letter, including the first word.
11    Pascal,
12    /// Keep all letters uppercase and indicate word boundaries with underscores.
13    ScreamingSnake,
14    /// Keep all letters lowercase and indicate word boundaries with underscores.
15    Snake,
16    /// Keep all letters lowercase and remove word boundaries.
17    Lower,
18    /// Keep all letters uppercase and remove word boundaries.
19    Upper,
20    /// Use the original attribute name defined in the code.
21    Verbatim,
22}
23
24impl CasingStyle {
25    pub fn from_lit(name: &syn::LitStr) -> Result<Self, Error> {
26        use self::CasingStyle::*;
27        use heck::ToUpperCamelCase;
28
29        let normalized = name.value().to_upper_camel_case().to_lowercase();
30
31        match normalized.as_ref() {
32            "camel" | "camelcase" => Ok(Camel),
33            "kebab" | "kebabcase" => Ok(Kebab),
34            "pascal" | "pascalcase" => Ok(Pascal),
35            "screamingsnake" | "screamingsnakecase" => Ok(ScreamingSnake),
36            "snake" | "snakecase" => Ok(Snake),
37            "lower" | "lowercase" => Ok(Lower),
38            "upper" | "uppercase" => Ok(Upper),
39            "verbatim" | "verbatimcase" => Ok(Verbatim),
40            _ => Err(Error::new(format!("unsupported casing: `{:?}`", name.value()), name.span(), Some("supperted values are ['camelCase', 'kebab-case', 'PascalCase', 'SCREAMING_SNAKE_CASE', 'snake_case', 'lowercase', 'UPPERCASE', 'verbatim']".to_owned())))
41        }
42    }
43
44    pub fn cast(self, s: String) -> String {
45        use CasingStyle::*;
46
47        match self {
48            Pascal => heck::ToUpperCamelCase::to_upper_camel_case(s.as_str()),
49            Camel => heck::ToLowerCamelCase::to_lower_camel_case(s.as_str()),
50            Kebab => heck::ToKebabCase::to_kebab_case(s.as_str()),
51            Snake => heck::ToSnakeCase::to_snake_case(s.as_str()),
52            ScreamingSnake => heck::ToShoutySnakeCase::to_shouty_snake_case(s.as_str()),
53            Lower => heck::ToSnakeCase::to_snake_case(s.as_str()).replace('_', ""),
54            Upper => heck::ToShoutySnakeCase::to_shouty_snake_case(s.as_str()).replace('_', ""),
55            Verbatim => s,
56        }
57    }
58}