1 use crate::{capitalize, lowercase, transform}; 2 3 /// This trait defines a mixed case conversion. 4 /// 5 /// In mixedCase, word boundaries are indicated by capital letters, excepting 6 /// the first word. 7 /// 8 /// ## Example: 9 /// 10 /// ```rust 11 /// use heck::MixedCase; 12 /// 13 /// let sentence = "It is we who built these palaces and cities."; 14 /// assert_eq!(sentence.to_mixed_case(), "itIsWeWhoBuiltThesePalacesAndCities"); 15 /// ``` 16 pub trait MixedCase: ToOwned { 17 /// Convert this type to mixed case. to_mixed_case(&self) -> Self::Owned18 fn to_mixed_case(&self) -> Self::Owned; 19 } 20 21 impl MixedCase for str { to_mixed_case(&self) -> String22 fn to_mixed_case(&self) -> String { 23 transform( 24 self, 25 |s, out| { 26 if out.is_empty() { 27 lowercase(s, out); 28 } else { 29 capitalize(s, out) 30 } 31 }, 32 |_| {}, 33 ) 34 } 35 } 36 37 #[cfg(test)] 38 mod tests { 39 use super::MixedCase; 40 41 macro_rules! t { 42 ($t:ident : $s1:expr => $s2:expr) => { 43 #[test] 44 fn $t() { 45 assert_eq!($s1.to_mixed_case(), $s2) 46 } 47 }; 48 } 49 50 t!(test1: "CamelCase" => "camelCase"); 51 t!(test2: "This is Human case." => "thisIsHumanCase"); 52 t!(test3: "MixedUP CamelCase, with some Spaces" => "mixedUpCamelCaseWithSomeSpaces"); 53 t!(test4: "mixed_up_ snake_case, with some _spaces" => "mixedUpSnakeCaseWithSomeSpaces"); 54 t!(test5: "kebab-case" => "kebabCase"); 55 t!(test6: "SHOUTY_SNAKE_CASE" => "shoutySnakeCase"); 56 t!(test7: "snake_case" => "snakeCase"); 57 t!(test8: "this-contains_ ALLKinds OfWord_Boundaries" => "thisContainsAllKindsOfWordBoundaries"); 58 t!(test9: "XΣXΣ baffle" => "xσxςBaffle"); 59 t!(test10: "XMLHttpRequest" => "xmlHttpRequest"); 60 // TODO unicode tests 61 } 62