-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
anchored_system_path_buf.rs
51 lines (40 loc) · 1.38 KB
/
anchored_system_path_buf.rs
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
use std::path::{Path, PathBuf};
use serde::Serialize;
use crate::{AbsoluteSystemPathBuf, IntoSystem, PathValidationError};
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize)]
pub struct AnchoredSystemPathBuf(PathBuf);
impl TryFrom<&Path> for AnchoredSystemPathBuf {
type Error = PathValidationError;
fn try_from(path: &Path) -> Result<Self, Self::Error> {
if path.is_absolute() {
return Err(PathValidationError::NotRelative(path.to_path_buf()));
}
Ok(AnchoredSystemPathBuf(path.into_system()?))
}
}
impl AnchoredSystemPathBuf {
pub fn new(
root: &AbsoluteSystemPathBuf,
path: &AbsoluteSystemPathBuf,
) -> Result<Self, PathValidationError> {
let stripped_path = path
.as_path()
.strip_prefix(root.as_path())
.map_err(|_| PathValidationError::NotParent(root.to_string(), path.to_string()))?
.to_path_buf();
Ok(AnchoredSystemPathBuf(stripped_path))
}
pub fn as_path(&self) -> &Path {
self.0.as_path()
}
pub fn to_str(&self) -> Result<&str, PathValidationError> {
self.0
.to_str()
.ok_or_else(|| PathValidationError::InvalidUnicode(self.0.clone()))
}
}
impl From<AnchoredSystemPathBuf> for PathBuf {
fn from(path: AnchoredSystemPathBuf) -> PathBuf {
path.0
}
}