file_storage/path/storage_path.rs
1/// A file or folder path.
2///
3/// # Base Path & Relative Path
4/// Storage paths are divided into a base path and a relative path. The base path is effectively
5/// immutable, and the relative path is a sequence of segments divided by file-separators.
6///
7/// ```text
8/// Unix Example:
9/// Path: /the/path
10/// Base Path: /
11/// Relative Path: the/path
12///
13/// Windows Example:
14/// Path: C:\The\Path
15/// Base Path: C:\
16/// Relative Path: The\Path
17///
18/// URL Example:
19/// Path: https://example.com/the/path
20/// Base Path: https://example.com/
21/// Relative Path: the/path
22/// ```
23///
24/// # Files & Folders
25/// A storage path can be a file path or a folder path. These are mutually exclusive and
26/// exhaustive. A storage path is a folder path if it is equal to its base path or ends with a
27/// file-separator, otherwise it is a file path. This invariant can be broken with `unsafe`.
28#[derive(Clone, Debug)]
29pub struct StoragePath {
30 path: String,
31 base_len: usize,
32 file_separator: char,
33}
34
35impl StoragePath {
36 //! Construction
37
38 /// Creates a new storage path.
39 ///
40 /// # Safety
41 /// The `base_len` must be a valid char boundary in the `path`.
42 pub unsafe fn new<S>(path: S, base_len: usize, file_separator: char) -> Self
43 where
44 S: Into<String>,
45 {
46 let path: String = path.into();
47
48 debug_assert!(path.is_char_boundary(base_len));
49
50 Self {
51 path,
52 base_len,
53 file_separator,
54 }
55 }
56}
57
58impl StoragePath {
59 //! Properties
60
61 /// Gets the path string.
62 pub fn path(&self) -> &str {
63 self.path.as_str()
64 }
65
66 /// Gets the mutable path string.
67 ///
68 /// # Safety
69 /// The path string must remain valid for the path.
70 pub unsafe fn path_mut(&mut self) -> &mut String {
71 &mut self.path
72 }
73
74 /// Gets the base length. (in bytes)
75 pub fn base_len(&self) -> usize {
76 self.base_len
77 }
78
79 /// Gets the file-separator.
80 pub fn file_separator(&self) -> char {
81 self.file_separator
82 }
83}
84
85#[cfg(test)]
86mod tests {
87 use crate::StoragePath;
88
89 #[test]
90 fn properties() {
91 let mut path: StoragePath = unsafe { StoragePath::new("/the/path", 1, '/') };
92 assert_eq!(path.path(), "/the/path");
93 unsafe {
94 assert_eq!(path.path_mut(), "/the/path");
95 }
96 assert_eq!(path.base_len(), 1);
97 assert_eq!(path.file_separator(), '/');
98 }
99}