lightning_types/
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
12use alloc::string::String;
13use core::fmt;
14
15/// Struct to `Display` fields in a safe way using `PrintableString`
16#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
17pub struct UntrustedString(pub String);
18
19impl fmt::Display for UntrustedString {
20	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
21		PrintableString(&self.0).fmt(f)
22	}
23}
24
25/// A string that displays only printable characters, replacing control characters with
26/// [`core::char::REPLACEMENT_CHARACTER`].
27#[derive(Debug, PartialEq)]
28pub struct PrintableString<'a>(pub &'a str);
29
30impl<'a> fmt::Display for PrintableString<'a> {
31	fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
32		use core::fmt::Write;
33		for c in self.0.chars() {
34			let c = if c.is_control() { core::char::REPLACEMENT_CHARACTER } else { c };
35			f.write_char(c)?;
36		}
37
38		Ok(())
39	}
40}
41
42#[cfg(test)]
43mod tests {
44	use super::PrintableString;
45
46	#[test]
47	fn displays_printable_string() {
48		assert_eq!(
49			format!("{}", PrintableString("I \u{1F496} LDK!\t\u{26A1}")),
50			"I \u{1F496} LDK!\u{FFFD}\u{26A1}",
51		);
52	}
53}