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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use std::str::FromStr;
use serde::{Deserialize, Serialize};
use cosmic_nom::new_span;
use crate::err::UniErr;
use crate::parse::consume_path;
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq, Hash)]
pub struct Path {
string: String,
}
impl Path {
fn new(string: &str) -> Self {
Path {
string: string.to_string(),
}
}
pub fn make_absolute(string: &str) -> Result<Self, UniErr> {
if string.starts_with("/") {
Path::from_str(string)
} else {
Path::from_str(format!("/{}", string).as_str())
}
}
pub fn bin(&self) -> Result<Vec<u8>, UniErr> {
let bin = bincode::serialize(self)?;
Ok(bin)
}
pub fn is_absolute(&self) -> bool {
self.string.starts_with("/")
}
pub fn cat(&self, path: &Path) -> Result<Self, UniErr> {
if self.string.ends_with("/") {
Path::from_str(format!("{}{}", self.string.as_str(), path.string.as_str()).as_str())
} else {
Path::from_str(format!("{}/{}", self.string.as_str(), path.string.as_str()).as_str())
}
}
pub fn parent(&self) -> Option<Path> {
let s = self.to_string();
let parent = std::path::Path::new(s.as_str()).parent();
match parent {
None => Option::None,
Some(path) => match path.to_str() {
None => Option::None,
Some(some) => match Self::from_str(some) {
Ok(parent) => Option::Some(parent),
Err(error) => {
eprintln!("{}", error.to_string());
Option::None
}
},
},
}
}
pub fn last_segment(&self) -> Option<String> {
let split = self.string.split("/");
match split.last() {
None => Option::None,
Some(last) => Option::Some(last.to_string()),
}
}
pub fn to_relative(&self) -> String {
let mut rtn = self.string.clone();
rtn.remove(0);
rtn
}
}
impl FromStr for Path {
type Err = UniErr;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (_, path) = consume_path(new_span(s))?;
Ok(Self {
string: path.to_string(),
})
}
}
impl ToString for Path {
fn to_string(&self) -> String {
self.string.clone()
}
}