1use alloc::format;
2use alloc::string::{String, ToString};
3use alloc::vec::Vec;
4use std::str::FromStr;
5
6use serde::{Deserialize, Serialize};
7
8use cosmic_nom::new_span;
9
10use crate::err::SpaceErr;
11use crate::parse::consume_path;
12
13#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq, Hash)]
14pub struct Path {
15 string: String,
16}
17
18impl Path {
19 fn new(string: &str) -> Self {
20 Path {
21 string: string.to_string(),
22 }
23 }
24
25 pub fn make_absolute(string: &str) -> Result<Self, SpaceErr> {
26 if string.starts_with("/") {
27 Path::from_str(string)
28 } else {
29 Path::from_str(format!("/{}", string).as_str())
30 }
31 }
32
33 pub fn bin(&self) -> Result<Vec<u8>, SpaceErr> {
34 let bin = bincode::serialize(self)?;
35 Ok(bin)
36 }
37
38 pub fn is_absolute(&self) -> bool {
39 self.string.starts_with("/")
40 }
41
42 pub fn cat(&self, path: &Path) -> Result<Self, SpaceErr> {
43 if self.string.ends_with("/") {
44 Path::from_str(format!("{}{}", self.string.as_str(), path.string.as_str()).as_str())
45 } else {
46 Path::from_str(format!("{}/{}", self.string.as_str(), path.string.as_str()).as_str())
47 }
48 }
49
50 pub fn parent(&self) -> Option<Path> {
51 let s = self.to_string();
52 let parent = std::path::Path::new(s.as_str()).parent();
53 match parent {
54 None => Option::None,
55 Some(path) => match path.to_str() {
56 None => Option::None,
57 Some(some) => match Self::from_str(some) {
58 Ok(parent) => Option::Some(parent),
59 Err(error) => {
60 eprintln!("{}", error.to_string());
61 Option::None
62 }
63 },
64 },
65 }
66 }
67
68 pub fn last_segment(&self) -> Option<String> {
69 let split = self.string.split("/");
70 match split.last() {
71 None => Option::None,
72 Some(last) => Option::Some(last.to_string()),
73 }
74 }
75
76 pub fn to_relative(&self) -> String {
77 let mut rtn = self.string.clone();
78 rtn.remove(0);
79 rtn
80 }
81}
82
83impl FromStr for Path {
84 type Err = SpaceErr;
85
86 fn from_str(s: &str) -> Result<Self, Self::Err> {
87 let (_, path) = consume_path(new_span(s))?;
88 Ok(Self {
89 string: path.to_string(),
90 })
91 }
92}
93
94impl ToString for Path {
95 fn to_string(&self) -> String {
96 self.string.clone()
97 }
98}