-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
anchored_system_path_buf.rs
53 lines (42 loc) · 1.48 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
52
53
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use crate::{AbsoluteSystemPath, IntoSystem, PathError, PathValidationError};
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
pub struct AnchoredSystemPathBuf(PathBuf);
impl TryFrom<&Path> for AnchoredSystemPathBuf {
type Error = PathError;
fn try_from(path: &Path) -> Result<Self, Self::Error> {
if path.is_absolute() {
return Err(PathValidationError::NotRelative(path.to_path_buf()).into());
}
Ok(AnchoredSystemPathBuf(path.into_system()?))
}
}
impl AnchoredSystemPathBuf {
pub fn new(
root: impl AsRef<AbsoluteSystemPath>,
path: impl AsRef<AbsoluteSystemPath>,
) -> Result<Self, PathError> {
let root = root.as_ref();
let path = path.as_ref();
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, PathError> {
self.0
.to_str()
.ok_or_else(|| PathValidationError::InvalidUnicode(self.0.clone()).into())
}
}
impl From<AnchoredSystemPathBuf> for PathBuf {
fn from(path: AnchoredSystemPathBuf) -> PathBuf {
path.0
}
}