summaryrefslogtreecommitdiffstats
path: root/crates/common/tedge_config/src/models/file_path.rs
blob: 62ef5723108045261035b615b9faf6f3c1f8dbd0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
use std::convert::TryInto;
use std::path::{Path, PathBuf};

/// Represents a path to a file or directory.
///
/// We need this newtype in order to implement `TryInto<String>`.
/// `PathBuf` does not implement `TryInto<String>`.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq)]
#[serde(transparent)]
pub struct FilePath(PathBuf);

#[derive(thiserror::Error, Debug)]
#[error("FilePath to String conversion failed: {0:?}")]
pub struct FilePathToStringConversionFailure(std::ffi::OsString);

impl<T> From<T> for FilePath
where
    PathBuf: From<T>,
{
    fn from(input: T) -> Self {
        Self(PathBuf::from(input))
    }
}

impl TryInto<String> for FilePath {
    type Error = FilePathToStringConversionFailure;

    fn try_into(self) -> Result<String, FilePathToStringConversionFailure> {
        self.0
            .into_os_string()
            .into_string()
            .map_err(FilePathToStringConversionFailure)
    }
}

impl AsRef<Path> for FilePath {
    fn as_ref(&self) -> &Path {
        self.0.as_ref()
    }
}

impl std::fmt::Display for FilePath {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0.display())
    }
}

impl Into<PathBuf> for FilePath {
    fn into(self) -> PathBuf {
        PathBuf::from(self.0)
    }
}