]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/util/string.rs
Add PrintableString utility
[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 core::fmt;
13
14 /// A string that displays only printable characters, replacing control characters with
15 /// [`core::char::REPLACEMENT_CHARACTER`].
16 pub struct PrintableString<'a>(pub &'a str);
17
18 impl<'a> fmt::Display for PrintableString<'a> {
19         fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
20                 use core::fmt::Write;
21                 for c in self.0.chars() {
22                         let c = if c.is_control() { core::char::REPLACEMENT_CHARACTER } else { c };
23                         f.write_char(c)?;
24                 }
25
26                 Ok(())
27         }
28 }
29
30 #[cfg(test)]
31 mod tests {
32         use super::PrintableString;
33
34         #[test]
35         fn displays_printable_string() {
36                 assert_eq!(
37                         format!("{}", PrintableString("I \u{1F496} LDK!\t\u{26A1}")),
38                         "I \u{1F496} LDK!\u{FFFD}\u{26A1}",
39                 );
40         }
41 }