6949c936e00e575ad8b4a848e61ee892a65b3eca
[rust-lightning] / lightning / src / util / string.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Utilities for strings.
11
12 use alloc::string::String;
13 use core::fmt;
14 use crate::io::{self, Read};
15 use crate::ln::msgs;
16 use crate::util::ser::{Writeable, Writer, Readable};
17
18 /// Struct to `Display` fields in a safe way using `PrintableString`
19 #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
20 pub struct UntrustedString(pub String);
21
22 impl Writeable for UntrustedString {
23         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
24                 self.0.write(w)
25         }
26 }
27
28 impl Readable for UntrustedString {
29         fn read<R: Read>(r: &mut R) -> Result<Self, msgs::DecodeError> {
30                 let s: String = Readable::read(r)?;
31                 Ok(Self(s))
32         }
33 }
34
35 impl fmt::Display for UntrustedString {
36         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
37                 PrintableString(&self.0).fmt(f)
38         }
39 }
40
41 /// A string that displays only printable characters, replacing control characters with
42 /// [`core::char::REPLACEMENT_CHARACTER`].
43 #[derive(Debug, PartialEq)]
44 pub struct PrintableString<'a>(pub &'a str);
45
46 impl<'a> fmt::Display for PrintableString<'a> {
47         fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
48                 use core::fmt::Write;
49                 for c in self.0.chars() {
50                         let c = if c.is_control() { core::char::REPLACEMENT_CHARACTER } else { c };
51                         f.write_char(c)?;
52                 }
53
54                 Ok(())
55         }
56 }
57
58 #[cfg(test)]
59 mod tests {
60         use super::PrintableString;
61
62         #[test]
63         fn displays_printable_string() {
64                 assert_eq!(
65                         format!("{}", PrintableString("I \u{1F496} LDK!\t\u{26A1}")),
66                         "I \u{1F496} LDK!\u{FFFD}\u{26A1}",
67                 );
68         }
69 }