smart_format/case/
capitalize.rs1use crate::prelude::*;
2
3pub struct Capitalize<T: fmt::Display>(pub T);
4
5impl<T: fmt::Display> fmt::Display for Capitalize<T> {
6 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7 use fmt::Write;
8
9 let mut first = true;
10
11 self.0.format_with(move |s: Option<&str>| {
12 let Some(s) = s else { return Ok(()) };
13 let mut i = s.chars();
14
15 if first {
16 for c in i.next().into_iter().flat_map(char::to_uppercase) {
17 first = false;
18 f.write_char(c)?;
19 }
20 }
21
22 for c in i.flat_map(char::to_lowercase) {
23 f.write_char(c)?;
24 }
25
26 Ok(())
27 })?;
28
29 Ok(())
30 }
31}
32
33#[cfg(test)]
34mod tests {
35 use super::super::tests::WORD_CASES;
36 use super::*;
37
38 #[test]
39 fn it_works() {
40 fn test_case(expected: &str, sample: &str) {
41 assert_eq!(expected, Capitalize(sample).to_string());
42 }
43
44 for &word in WORD_CASES {
45 test_case("Word", word);
46 }
47 }
48
49 #[test]
50 fn is_works_with_dyn_display() {
51 fn test_case(expected: &str, sample: &dyn fmt::Display) {
52 assert_eq!(expected, Capitalize(sample).to_string());
53 }
54
55 for &word in WORD_CASES {
56 test_case("Word", &word);
57 }
58 }
59}