standard_lib/fs/path/
display.rs1use std::ffi::OsStr;
2use std::fmt::{self, Display, Formatter};
3use std::marker::PhantomData;
4use std::os::unix::ffi::OsStrExt;
5
6use super::{Abs, OwnedPath, Path, Rel, PathState};
7
8pub struct DisplayPath<'a, State: PathState> {
9 pub(crate) _phantom: PhantomData<fn() -> State>,
10 pub(crate) inner: &'a Path<State>,
11}
12
13pub struct DisplayFull<'a> {
14 pub(crate) inner: &'a Path<Abs>,
15}
16
17pub struct DisplayHome<'a> {
18 pub(crate) inner: &'a Path<Abs>,
19}
20
21pub struct DisplayDotSlash<'a> {
22 pub(crate) inner: &'a Path<Rel>,
23}
24
25pub struct DisplaySlash<'a> {
26 pub(crate) inner: &'a Path<Rel>,
27}
28
29pub struct DisplayNoLead<'a> {
30 pub(crate) inner: &'a Path<Rel>,
31}
32
33impl<'a> DisplayPath<'a, Abs> {
34 pub const fn full(&self) -> DisplayFull<'a> {
35 DisplayFull {
36 inner: self.inner,
37 }
38 }
39
40 pub const fn shrink_home(&self) -> DisplayHome<'a> {
41 DisplayHome {
42 inner: self.inner,
43 }
44 }
45}
46
47impl<'a> Display for DisplayPath<'a, Abs> {
48 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
49 write!(f, "{}", self.full())
50 }
51}
52
53impl<'a> Display for DisplayFull<'a> {
54 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
55 write!(f, "{}", self.inner.as_os_str().to_string_lossy())
56 }
57}
58
59impl<'a> Display for DisplayHome<'a> {
60 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
61 if let Some(home) = OwnedPath::home()
62 && let Some(rel) = self.inner.relative(&home) {
63 write!(f, "~{}", rel.display().slash())
64 } else {
65 write!(f, "{}", self.inner.as_os_str().to_string_lossy())
66 }
67 }
68}
69
70impl<'a> DisplayPath<'a, Rel> {
71 pub const fn dot_slash(&self) -> DisplayDotSlash<'a> {
72 DisplayDotSlash {
73 inner: self.inner,
74 }
75 }
76
77 pub const fn slash(&self) -> DisplaySlash<'a> {
78 DisplaySlash {
79 inner: self.inner,
80 }
81 }
82
83 pub const fn no_lead(&self) -> DisplayNoLead<'a> {
84 DisplayNoLead {
85 inner: self.inner,
86 }
87 }
88}
89
90impl<'a> Display for DisplayPath<'a, Rel> {
91 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
92 write!(f, "{}", self.dot_slash())
93 }
94}
95
96impl<'a> Display for DisplayDotSlash<'a> {
97 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
98 write!(f, ".{}", self.inner.as_os_str().to_string_lossy())
99 }
100}
101
102impl<'a> Display for DisplaySlash<'a> {
103 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
104 write!(f, "{}", self.inner.as_os_str().to_string_lossy())
105 }
106}
107
108impl<'a> Display for DisplayNoLead<'a> {
109 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
110 write!(f, "{}", OsStr::from_bytes(
111 &self.inner.as_os_str().as_bytes()[1..]
112 ).to_string_lossy())
113 }
114}