vortex_utils/aliases/
string_escape.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::fmt::Debug;
5use std::fmt::Display;
6use std::fmt::Formatter;
7
8/// A wrapper around a string that implements `Display` for a string while removing all unicode
9/// escape sequences.
10#[derive(Debug)]
11pub struct StringEscape<'a>(pub &'a str);
12
13impl Display for StringEscape<'_> {
14    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
15        write!(f, "{}", self.0.escape_debug())
16    }
17}
18
19#[cfg(test)]
20mod tests {
21    use crate::aliases::string_escape::StringEscape;
22
23    #[test]
24    fn test_no_escape_string() {
25        let s = StringEscape("hello");
26        assert_eq!(s.to_string(), "hello");
27    }
28
29    #[test]
30    fn test_heart_string() {
31        let s = StringEscape("hello ♡");
32        assert_eq!(s.to_string(), "hello ♡");
33    }
34
35    #[test]
36    fn test_string_escape() {
37        let s = StringEscape("\"\n\t\r\\\0\x1f\x7f");
38        assert_eq!(s.to_string(), "\\\"\\n\\t\\r\\\\\\0\\u{1f}\\u{7f}");
39    }
40}