1 use core::fmt; 2 3 use alloc::{borrow::ToOwned, string::ToString}; 4 5 use crate::{transform, uppercase}; 6 7 /// This trait defines a shouty kebab case conversion. 8 /// 9 /// In SHOUTY-KEBAB-CASE, word boundaries are indicated by hyphens and all 10 /// words are in uppercase. 11 /// 12 /// ## Example: 13 /// 14 /// ```rust 15 /// use heck::ToShoutyKebabCase; 16 /// 17 /// let sentence = "We are going to inherit the earth."; 18 /// assert_eq!(sentence.to_shouty_kebab_case(), "WE-ARE-GOING-TO-INHERIT-THE-EARTH"); 19 /// ``` 20 pub trait ToShoutyKebabCase: ToOwned { 21 /// Convert this type to shouty kebab case. to_shouty_kebab_case(&self) -> Self::Owned22 fn to_shouty_kebab_case(&self) -> Self::Owned; 23 } 24 25 impl ToShoutyKebabCase for str { to_shouty_kebab_case(&self) -> Self::Owned26 fn to_shouty_kebab_case(&self) -> Self::Owned { 27 AsShoutyKebabCase(self).to_string() 28 } 29 } 30 31 /// This wrapper performs a kebab case conversion in [`fmt::Display`]. 32 /// 33 /// ## Example: 34 /// 35 /// ``` 36 /// use heck::AsShoutyKebabCase; 37 /// 38 /// let sentence = "We are going to inherit the earth."; 39 /// assert_eq!(format!("{}", AsShoutyKebabCase(sentence)), "WE-ARE-GOING-TO-INHERIT-THE-EARTH"); 40 /// ``` 41 pub struct AsShoutyKebabCase<T: AsRef<str>>(pub T); 42 43 impl<T: AsRef<str>> fmt::Display for AsShoutyKebabCase<T> { fmt(&self, f: &mut fmt::Formatter) -> fmt::Result44 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 45 transform(self.0.as_ref(), uppercase, |f| write!(f, "-"), f) 46 } 47 } 48 49 #[cfg(test)] 50 mod tests { 51 use super::ToShoutyKebabCase; 52 53 macro_rules! t { 54 ($t:ident : $s1:expr => $s2:expr) => { 55 #[test] 56 fn $t() { 57 assert_eq!($s1.to_shouty_kebab_case(), $s2) 58 } 59 }; 60 } 61 62 t!(test1: "CamelCase" => "CAMEL-CASE"); 63 t!(test2: "This is Human case." => "THIS-IS-HUMAN-CASE"); 64 t!(test3: "MixedUP CamelCase, with some Spaces" => "MIXED-UP-CAMEL-CASE-WITH-SOME-SPACES"); 65 t!(test4: "mixed_up_ snake_case with some _spaces" => "MIXED-UP-SNAKE-CASE-WITH-SOME-SPACES"); 66 t!(test5: "kebab-case" => "KEBAB-CASE"); 67 t!(test6: "SHOUTY_SNAKE_CASE" => "SHOUTY-SNAKE-CASE"); 68 t!(test7: "snake_case" => "SNAKE-CASE"); 69 t!(test8: "this-contains_ ALLKinds OfWord_Boundaries" => "THIS-CONTAINS-ALL-KINDS-OF-WORD-BOUNDARIES"); 70 t!(test9: "XΣXΣ baffle" => "XΣXΣ-BAFFLE"); 71 t!(test10: "XMLHttpRequest" => "XML-HTTP-REQUEST"); 72 t!(test11: "SHOUTY-KEBAB-CASE" => "SHOUTY-KEBAB-CASE"); 73 } 74