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.
13 use crate::io::{self, Read};
15 use crate::util::ser::{Writeable, Writer, Readable};
17 #[allow(unused_imports)]
18 use crate::prelude::*;
20 /// Struct to `Display` fields in a safe way using `PrintableString`
21 #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
22 pub struct UntrustedString(pub String);
24 impl Writeable for UntrustedString {
25 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
30 impl Readable for UntrustedString {
31 fn read<R: Read>(r: &mut R) -> Result<Self, msgs::DecodeError> {
32 let s: String = Readable::read(r)?;
37 impl fmt::Display for UntrustedString {
38 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
39 PrintableString(&self.0).fmt(f)
43 /// A string that displays only printable characters, replacing control characters with
44 /// [`core::char::REPLACEMENT_CHARACTER`].
45 #[derive(Debug, PartialEq)]
46 pub struct PrintableString<'a>(pub &'a str);
48 impl<'a> fmt::Display for PrintableString<'a> {
49 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
51 for c in self.0.chars() {
52 let c = if c.is_control() { core::char::REPLACEMENT_CHARACTER } else { c };
62 use super::PrintableString;
65 fn displays_printable_string() {
67 format!("{}", PrintableString("I \u{1F496} LDK!\t\u{26A1}")),
68 "I \u{1F496} LDK!\u{FFFD}\u{26A1}",