typed_path/common/non_utf8/path/display.rs
1use core::fmt;
2
3use crate::no_std_compat::*;
4use crate::{Encoding, Path};
5
6/// Helper struct for safely printing paths with [`format!`] and `{}`.
7///
8/// A [`Path`] might contain non-Unicode data. This `struct` implements the
9/// [`Display`] trait in a way that mitigates that. It is created by the
10/// [`display`](Path::display) method on [`Path`]. This may perform lossy
11/// conversion, depending on the platform. If you would like an implementation
12/// which escapes the path please use [`Debug`] instead.
13///
14/// # Examples
15///
16/// ```
17/// use typed_path::{Path, UnixEncoding};
18///
19/// // NOTE: A path cannot be created on its own without a defined encoding
20/// let path = Path::<UnixEncoding>::new("/tmp/foo.rs");
21///
22/// println!("{}", path.display());
23/// ```
24///
25/// [`Display`]: fmt::Display
26/// [`format!`]: std::format
27pub struct Display<'a, T>
28where
29 T: Encoding,
30{
31 pub(crate) path: &'a Path<T>,
32}
33
34impl<T> fmt::Debug for Display<'_, T>
35where
36 T: Encoding,
37{
38 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39 fmt::Debug::fmt(&self.path, f)
40 }
41}
42
43impl<T> fmt::Display for Display<'_, T>
44where
45 T: Encoding,
46{
47 /// Performs lossy conversion to UTF-8 str
48 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49 write!(f, "{}", String::from_utf8_lossy(&self.path.inner))
50 }
51}