async_smtp/
util.rs

1//! Utils for string manipulation
2
3use std::fmt::{Display, Formatter, Result as FmtResult};
4
5/// Encode a string as xtext
6///
7/// xtext is defined in <https://www.rfc-editor.org/rfc/rfc3461>
8#[derive(Debug)]
9pub struct XText<'a>(pub &'a str);
10
11impl Display for XText<'_> {
12    fn fmt(&self, f: &mut Formatter) -> FmtResult {
13        for c in self.0.chars() {
14            if c < '!' || c == '+' || c == '=' {
15                write!(f, "+{:X}", c as u8)?;
16            } else {
17                write!(f, "{c}")?;
18            }
19        }
20        Ok(())
21    }
22}
23
24#[cfg(test)]
25mod tests {
26    use super::XText;
27
28    #[test]
29    fn test() {
30        for (input, expect) in [
31            ("bjorn", "bjorn"),
32            ("bjørn", "bjørn"),
33            ("Ø+= ❤️‰", "Ø+2B+3D+20❤️‰"),
34            ("+", "+2B"),
35        ] {
36            assert_eq!(format!("{}", XText(input)), expect.to_string());
37        }
38    }
39}