1 // This file is Copyright its original authors, visible in version control
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
10 //! Utilities for strings.
12 use alloc::string::String;
14 use crate::io::{self, Read};
16 use crate::util::ser::{Writeable, Writer, Readable};
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);
22 impl Writeable for UntrustedString {
23 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
28 impl Readable for UntrustedString {
29 fn read<R: Read>(r: &mut R) -> Result<Self, msgs::DecodeError> {
30 let s: String = Readable::read(r)?;
35 impl fmt::Display for UntrustedString {
36 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
37 PrintableString(&self.0).fmt(f)
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);
46 impl<'a> fmt::Display for PrintableString<'a> {
47 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
49 for c in self.0.chars() {
50 let c = if c.is_control() { core::char::REPLACEMENT_CHARACTER } else { c };
60 use super::PrintableString;
63 fn displays_printable_string() {
65 format!("{}", PrintableString("I \u{1F496} LDK!\t\u{26A1}")),
66 "I \u{1F496} LDK!\u{FFFD}\u{26A1}",