fmty/convert_case/
mod.rs

1use core::fmt::*;
2
3mod tests;
4
5pub(crate) mod types {
6    #[allow(unused)]
7    use super::*;
8
9    /// See [`to_ascii_uppercase()`].
10    #[derive(Clone, Copy)]
11    pub struct ToAsciiUppercase<T> {
12        pub(super) value: T,
13    }
14
15    /// See [`to_ascii_lowercase()`].
16    #[derive(Clone, Copy)]
17    pub struct ToAsciiLowercase<T> {
18        pub(super) value: T,
19    }
20}
21
22use types::*;
23
24/// Converts to ASCII uppercase.
25///
26/// This may be used as a non-allocating alternative to
27/// [`str::to_ascii_uppercase()`](https://doc.rust-lang.org/std/primitive.str.html#method.to_ascii_uppercase).
28///
29/// # Examples
30///
31/// ```
32/// let value = fmty::to_ascii_uppercase("Grüße, Jürgen ❤");
33/// assert_eq!(value.to_string(), "GRüßE, JüRGEN ❤");
34/// ```
35pub fn to_ascii_uppercase<T>(value: T) -> ToAsciiUppercase<T> {
36    ToAsciiUppercase { value }
37}
38
39/// Converts to ASCII lowercase.
40///
41/// This may be used as a non-allocating alternative to
42/// [`str::to_ascii_lowercase()`](https://doc.rust-lang.org/std/primitive.str.html#method.to_ascii_lowercase).
43///
44/// # Examples
45///
46/// ```
47/// let value = fmty::to_ascii_lowercase("Grüße, Jürgen ❤");
48/// assert_eq!(value.to_string(), "grüße, jürgen ❤");
49/// ```
50pub fn to_ascii_lowercase<T>(value: T) -> ToAsciiLowercase<T> {
51    ToAsciiLowercase { value }
52}
53
54/// Single writer for ASCII to reduce code generation.
55struct AsciiWriter<'a, 'b> {
56    f: &'b mut Formatter<'a>,
57    uppercase: bool,
58}
59
60impl Write for AsciiWriter<'_, '_> {
61    fn write_str(&mut self, s: &str) -> Result {
62        for c in s.chars() {
63            self.write_char(c)?;
64        }
65        Ok(())
66    }
67
68    fn write_char(&mut self, c: char) -> Result {
69        self.f.write_char(if self.uppercase {
70            c.to_ascii_uppercase()
71        } else {
72            c.to_ascii_lowercase()
73        })
74    }
75}
76
77impl<T: Debug> Debug for ToAsciiLowercase<T> {
78    fn fmt(&self, f: &mut Formatter) -> Result {
79        write!(AsciiWriter { f, uppercase: false }, "{:?}", self.value)
80    }
81}
82
83impl<T: Display> Display for ToAsciiLowercase<T> {
84    fn fmt(&self, f: &mut Formatter) -> Result {
85        write!(AsciiWriter { f, uppercase: false }, "{}", self.value)
86    }
87}
88
89impl<T: Debug> Debug for ToAsciiUppercase<T> {
90    fn fmt(&self, f: &mut Formatter) -> Result {
91        write!(AsciiWriter { f, uppercase: true }, "{:?}", self.value)
92    }
93}
94
95impl<T: Display> Display for ToAsciiUppercase<T> {
96    fn fmt(&self, f: &mut Formatter) -> Result {
97        write!(AsciiWriter { f, uppercase: true }, "{}", self.value)
98    }
99}