]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/util/string.rs
Merge pull request #1892 from tnull/2022-12-spendableoutputdescriptor-doccs
[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 #[derive(Debug, PartialEq)]
17 pub struct PrintableString<'a>(pub &'a str);
18
19 impl<'a> fmt::Display for PrintableString<'a> {
20         fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
21                 use core::fmt::Write;
22                 for c in self.0.chars() {
23                         let c = if c.is_control() { core::char::REPLACEMENT_CHARACTER } else { c };
24                         f.write_char(c)?;
25                 }
26
27                 Ok(())
28         }
29 }
30
31 #[cfg(test)]
32 mod tests {
33         use super::PrintableString;
34
35         #[test]
36         fn displays_printable_string() {
37                 assert_eq!(
38                         format!("{}", PrintableString("I \u{1F496} LDK!\t\u{26A1}")),
39                         "I \u{1F496} LDK!\u{FFFD}\u{26A1}",
40                 );
41         }
42 }