1use std::fmt;
2
3use crate::{capitalize, transform};
4
5/// This trait defines a title case conversion.
6///
7/// In Title Case, word boundaries are indicated by spaces, and every word is
8/// capitalized.
9///
10/// ## Example:
11///
12/// ```rust
13/// use heck::ToTitleCase;
14///
15/// let sentence = "We have always lived in slums and holes in the wall.";
16/// assert_eq!(sentence.to_title_case(), "We Have Always Lived In Slums And Holes In The Wall");
17/// ```
18pub trait ToTitleCase: ToOwned {
19 /// Convert this type to title case.
20 fn to_title_case(&self) -> Self::Owned;
21}
22
23impl ToTitleCase for str {
24 fn to_title_case(&self) -> String {
25 AsTitleCase(self).to_string()
26 }
27}
28
29/// This wrapper performs a title case conversion in [`fmt::Display`].
30///
31/// ## Example:
32///
33/// ```
34/// use heck::AsTitleCase;
35///
36/// let sentence = "We have always lived in slums and holes in the wall.";
37/// assert_eq!(format!("{}", AsTitleCase(sentence)), "We Have Always Lived In Slums And Holes In The Wall");
38/// ```
39pub struct AsTitleCase<T: AsRef<str>>(pub T);
40
41impl<T: AsRef<str>> fmt::Display for AsTitleCase<T> {
42 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
43 transform(self.0.as_ref(), with_word:capitalize, |f: &mut Formatter<'_>| write!(f, " "), f)
44 }
45}
46
47#[cfg(test)]
48mod tests {
49 use super::ToTitleCase;
50
51 macro_rules! t {
52 ($t:ident : $s1:expr => $s2:expr) => {
53 #[test]
54 fn $t() {
55 assert_eq!($s1.to_title_case(), $s2)
56 }
57 };
58 }
59
60 t!(test1: "CamelCase" => "Camel Case");
61 t!(test2: "This is Human case." => "This Is Human Case");
62 t!(test3: "MixedUP CamelCase, with some Spaces" => "Mixed Up Camel Case With Some Spaces");
63 t!(test4: "mixed_up_ snake_case, with some _spaces" => "Mixed Up Snake Case With Some Spaces");
64 t!(test5: "kebab-case" => "Kebab Case");
65 t!(test6: "SHOUTY_SNAKE_CASE" => "Shouty Snake Case");
66 t!(test7: "snake_case" => "Snake Case");
67 t!(test8: "this-contains_ ALLKinds OfWord_Boundaries" => "This Contains All Kinds Of Word Boundaries");
68 #[cfg(feature = "unicode")]
69 t!(test9: "XΣXΣ baffle" => "Xσxς Baffle");
70 t!(test10: "XMLHttpRequest" => "Xml Http Request");
71}
72