serde_loader/
abs_path_buf.rs1use crate::{common::*, dir_stack::try_rebase_path};
2
3#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4#[repr(transparent)]
5pub struct AbsPathBuf(PathBuf);
6
7impl AbsPathBuf {
8 pub fn get(&self) -> &PathBuf {
9 &self.0
10 }
11
12 pub fn into_inner(self) -> PathBuf {
13 self.0
14 }
15}
16
17impl TryFrom<&'_ OsStr> for AbsPathBuf {
18 type Error = anyhow::Error;
19
20 fn try_from(from: &'_ OsStr) -> Result<Self, Self::Error> {
21 let path = Path::new(from);
22 let path = try_rebase_path(path);
23 Ok(Self(path.into_owned()))
24 }
25}
26
27impl TryFrom<&'_ Path> for AbsPathBuf {
28 type Error = anyhow::Error;
29
30 fn try_from(from: &'_ Path) -> Result<Self, Self::Error> {
31 Self::try_from(from.as_os_str())
32 }
33}
34
35impl TryFrom<&'_ PathBuf> for AbsPathBuf {
36 type Error = anyhow::Error;
37
38 fn try_from(from: &PathBuf) -> Result<Self, Self::Error> {
39 Self::try_from(from.as_os_str())
40 }
41}
42
43impl TryFrom<PathBuf> for AbsPathBuf {
44 type Error = anyhow::Error;
45
46 fn try_from(from: PathBuf) -> Result<Self, Self::Error> {
47 Self::try_from(from.as_os_str())
48 }
49}
50
51impl AsRef<Path> for AbsPathBuf {
52 fn as_ref(&self) -> &Path {
53 self.0.as_ref()
54 }
55}
56
57impl Deref for AbsPathBuf {
58 type Target = Path;
59
60 fn deref(&self) -> &Self::Target {
61 self.0.deref()
62 }
63}
64
65impl Serialize for AbsPathBuf {
66 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
67 where
68 S: Serializer,
69 {
70 let path = &self.0;
71 assert!(path.is_absolute(), "please report bug");
72
73 path.serialize(serializer)
74 }
75}
76
77impl<'de> Deserialize<'de> for AbsPathBuf {
78 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
79 where
80 D: Deserializer<'de>,
81 {
82 let path = PathBuf::deserialize(deserializer)?;
83 let path = Self::try_from(&path).map_err(|_| {
84 D::Error::custom(format!(
85 "unable to resolve the absolute path of '{}'",
86 path.display()
87 ))
88 })?;
89
90 Ok(path)
91 }
92}