Skip to main content

simple_path/
display.rs

1use crate::SimplePath;
2use std::{
3    fmt,
4    path::{self, Path},
5};
6
7/// Helper struct for printing simplified paths with [`format!`] and `{}`.
8///
9/// Please see [`SimplePath::display`].
10#[derive(Debug)]
11pub struct Display<'a> {
12    #[cfg(windows)]
13    simple: &'a SimplePath,
14    path: &'a Path,
15}
16
17impl<'a> Display<'a> {
18    #[cfg(windows)]
19    pub(crate) fn new(simple: &'a SimplePath, path: &'a Path) -> Self {
20        Self { simple, path }
21    }
22    #[cfg(not(windows))]
23    pub(crate) fn new(_unc: &'a SimplePath, path: &'a Path) -> Self {
24        Self { path }
25    }
26}
27
28impl fmt::Display for Display<'_> {
29    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30        #[cfg(windows)]
31        if let Ok(Some(simplified)) = self.simple.simplify(self.path) {
32            return path::Display::fmt(&simplified.display(), f);
33        };
34        path::Display::fmt(&self.path.display(), f)
35    }
36}
37
38#[cfg(test)]
39mod tests {
40    use super::*;
41
42    #[test]
43    fn display_not_simplified() {
44        let simple = SimplePath::default();
45        let path = Path::new("foo");
46        assert_eq!(format!("{}", simple.display(path)), "foo");
47    }
48
49    #[cfg(windows)]
50    #[test]
51    fn display_drive_unc() {
52        let mut simple = SimplePath::mock();
53        let path = Path::new(r"\\?\UNC\server\share\foo");
54        assert_eq!(format!("{}", simple.display(path)), r"\\server\share\foo");
55
56        simple.map_to_drive = true;
57        assert_eq!(format!("{}", simple.display(path)), r"X:\foo");
58    }
59}