File_system/Fundamentals/Path/
Path_owned.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
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
use std::{
    fmt::{Display, Formatter},
    ops::Deref,
};

use super::{Extension_separator, Path_type, Separator};

#[derive(Clone, PartialEq, Eq, Debug, Hash)]
#[repr(transparent)]
pub struct Path_owned_type(String);

impl Path_owned_type {
    /// # Safety
    /// The caller must ensure that the string is valid path string.
    pub unsafe fn New_unchecked(Path: String) -> Self {
        Path_owned_type(Path)
    }

    pub fn New(Path: String) -> Option<Self> {
        let Path = if Path.ends_with(Separator) && Path.len() > 1 {
            Path[..Path.len() - 1].to_string()
        } else {
            Path
        };

        if Is_valid_string(&Path) {
            Some(Path_owned_type(Path))
        } else {
            None
        }
    }

    pub fn Root() -> Path_owned_type {
        Path_owned_type("/".to_string())
    }

    pub fn Join(mut self, Path: impl AsRef<Path_type>) -> Option<Self> {
        if Path.as_ref().Is_absolute() {
            return None;
        }

        if Path.as_ref().Is_empty() {
            return Some(self);
        }

        if !self.0.ends_with(Separator) {
            self.0.push(Separator);
        }
        self.0.push_str(Path.as_ref().As_str());

        Some(self)
    }

    pub fn Append(self, Path: &str) -> Option<Self> {
        self.Join(Path_type::From_str(Path))
    }

    pub fn Revert_parent_directory(&mut self) -> &mut Self {
        let mut Last_index = 0;
        for (i, c) in self.0.chars().enumerate() {
            if c == Separator {
                Last_index = i;
            }
        }
        if Last_index == 0 {
            self.0.clear();
            return self;
        }

        self.0.truncate(Last_index);
        self
    }

    pub fn Get_extension(&self) -> Option<&str> {
        let mut extension = None;

        for (i, c) in self.0.chars().enumerate() {
            if c == Extension_separator {
                extension = Some(&self.0[i..]);
            }
        }
        extension
    }

    pub fn Get_file_name(&self) -> &str {
        let mut Last_index = 0;
        for (i, c) in self.0.chars().enumerate() {
            if c == Separator {
                Last_index = i;
            }
        }
        if Last_index >= self.0.len() {
            return &self.0[Last_index..];
        }
        &self.0[Last_index + 1..]
    }

    pub fn Get_relative_to(&self, Path: &Path_owned_type) -> Option<Path_owned_type> {
        if !self.0.starts_with(Path.0.as_str()) {
            return None;
        }

        Some(Path_owned_type(self.0[Path.0.len()..].to_string()))
    }

    pub fn Canonicalize(mut self) -> Self {
        let mut Stack: Vec<&str> = Vec::new();

        if self.Is_absolute() {
            Stack.push("");
        }

        for Component in self.0.split(Separator) {
            match Component {
                ".." => {
                    Stack.pop();
                }
                "." | "" => continue,
                _ => Stack.push(Component),
            }
        }

        self.0 = Stack.join("/");

        self
    }
}

pub fn Is_valid_string(String: &str) -> bool {
    let Invalid = ['\0', ':', '*', '?', '"', '<', '>', '|', ' '];

    for Character in String.chars() {
        // Check if the string contains invalid characters.
        if Invalid.contains(&Character) {
            return false;
        }
    }

    if String.ends_with(Separator) && String.len() > 1 {
        // Check if the string ends with a separator and is not the root directory.
        return false;
    }

    true
}

impl TryFrom<&str> for Path_owned_type {
    type Error = ();

    fn try_from(item: &str) -> Result<Self, Self::Error> {
        if Is_valid_string(item) {
            Ok(Path_owned_type(item.to_string()))
        } else {
            Err(())
        }
    }
}

impl TryFrom<String> for Path_owned_type {
    type Error = ();

    fn try_from(item: String) -> Result<Self, Self::Error> {
        if Is_valid_string(&item) {
            Ok(Path_owned_type(item))
        } else {
            Err(())
        }
    }
}

impl Display for Path_owned_type {
    fn fmt(&self, Formatter: &mut Formatter) -> Result<(), std::fmt::Error> {
        write!(Formatter, "{}", self.0)
    }
}

impl AsRef<str> for Path_owned_type {
    fn as_ref(&self) -> &str {
        self.0.as_str()
    }
}

impl Deref for Path_owned_type {
    type Target = Path_type;

    fn deref(&self) -> &Self::Target {
        Path_type::From_str(self.0.as_str())
    }
}

impl AsRef<Path_type> for Path_owned_type {
    fn as_ref(&self) -> &Path_type {
        self
    }
}

#[cfg(test)]
mod Tests {
    use super::*;

    #[test]
    fn Test_path_addition() {
        let Path = Path_owned_type::try_from("/").unwrap();
        assert_eq!(Path.As_str(), "/");
        let Path = Path.Append("Folder").unwrap();
        assert_eq!(Path.As_str(), "/Folder");
        let Path = Path.Append("File").unwrap();
        assert_eq!(Path.As_str(), "/Folder/File");
    }

    #[test]
    fn Test_valid_string() {
        assert!(Is_valid_string("Hello"));
        assert!(Is_valid_string("Hello/World"));
        assert!(Is_valid_string("Hello/World.txt"));
        assert!(!Is_valid_string("Hello/World.txt/"));
        assert!(!Is_valid_string("Hello/World.txt:"));
        assert!(!Is_valid_string("Hello/World.txt*"));
        assert!(!Is_valid_string("Hello/World.txt?"));
        assert!(!Is_valid_string("Hello/World.txt\""));
        assert!(!Is_valid_string("Hello/World.txt<"));
        assert!(!Is_valid_string("Hello/World.txt>"));
        assert!(!Is_valid_string("Hello/World.txt|"));
        assert!(!Is_valid_string("Hello/World.txt "));
        assert!(!Is_valid_string("Hello/World.txt\0"));
        assert!(Is_valid_string(""));
        assert!(!Is_valid_string("Hello/Wo rld.txt/"));
    }

    #[test]
    fn Test_canonicalize() {
        let Path = Path_owned_type::try_from("/home/../home/user/./file.txt").unwrap();
        assert_eq!(Path.Canonicalize().As_str(), "/home/user/file.txt");

        let Path = Path_owned_type::try_from("./home/../home/user/./file.txt").unwrap();
        assert_eq!(Path.Canonicalize().As_str(), "home/user/file.txt");
    }
}