Skip to main content

better_url/parts/path/entire/segmented/file/
set.rs

1//! Setters.
2
3use crate::prelude::*;
4
5// TODO: Optimize relatives.
6
7impl FilePath<'_> {
8    /// [`resolve_file_path_range`].
9    fn resolve_range<B: RangeBounds<usize>>(&mut self, range: B) -> bool {
10        let mut temp = "/".into();
11
12        std::mem::swap(&mut self.0, &mut temp);
13
14        let (changed, mut temp) = resolve_file_path_range(temp, range);
15
16        std::mem::swap(&mut self.0, &mut temp);
17
18        changed
19    }
20
21    /// Append `value`.
22    /// # Examples
23    /// ```
24    /// use better_url::prelude::*;
25    ///
26    /// let mut path = FilePath::new("/abc/def/ghi");
27    ///
28    /// path.push("123"); assert_eq!(path, "/abc/def/ghi/123");
29    /// path.push(".." ); assert_eq!(path, "/abc/def/ghi/"   );
30    /// path.push(".." ); assert_eq!(path, "/abc/def/ghi/"   );
31    /// path.push("."  ); assert_eq!(path, "/abc/def/ghi//"  );
32    /// ```
33    pub fn push<'a, T: Into<FilePathSegment<'a>>>(&mut self, value: T) -> bool {
34        let start = self.len();
35
36        self.0.extend(["/", value.into().as_str()]);
37
38        let _ = self.resolve_range(start..);
39
40        true
41    }
42
43    /// Prepend `value`.
44    /// # Examples
45    /// ```
46    /// use better_url::prelude::*;
47    ///
48    /// let mut path = FilePath::new("/abc/def/ghi");
49    ///
50    /// path.prepend("123"); assert_eq!(path, "/123/abc/def/ghi");
51    /// path.prepend("."  ); assert_eq!(path, "/123/abc/def/ghi");
52    /// path.prepend(".." ); assert_eq!(path, "/123/abc/def/ghi");
53    /// ```
54    pub fn prepend<'a, T: Into<FilePathSegment<'a>>>(&mut self, value: T) -> bool {
55        let new = value.into();
56
57        self.0.insert_with(0, ["/", new.as_str()]);
58
59        let _ = self.resolve_range(.. 1 + new.len());
60
61        true
62    }
63
64    /// Set, insert, or remove the `index`th segment.
65    ///
66    /// If `value` is [`None`] and `index` is out of bounds, does nothing.
67    /// # Errors
68    /// If `value` is [`Some`] and `index` is more than 1 out of bounds, returns the error [`InsertNotFound`].
69    ///
70    /// If `value` is [`None`] and `index` is the only segment, returns the error [`CantBeEmpty`].
71    /// # Examples
72    /// ```
73    /// use better_url::prelude::*;
74    ///
75    /// let mut path = FilePath::new("/c:/abc/def/ghi");
76    ///
77    /// path.set( 1, Some(".." )).unwrap(); assert_eq!(path, "/c:/def/ghi"    );
78    /// path.set( 0, Some("e|" )).unwrap(); assert_eq!(path, "/e:/def/ghi"    );
79    /// path.set(-4, Some("123")).unwrap(); assert_eq!(path, "/123/e:/def/ghi");
80    /// path.set( 2, Some(".." )).unwrap(); assert_eq!(path, "/123/ghi"       );
81    /// path.set( 2, Some("456")).unwrap(); assert_eq!(path, "/123/ghi/456"   );
82    /// ```
83    pub fn set<'a, T: Into<FilePathSegment<'a>>>(&mut self, index: isize, value: Option<T>) -> Result<bool, SetPathError> {
84        Ok(match value.map(Into::into) {
85            Some(new) => match (self.iter_strs().try_neg_nth(index), index) {
86                (Ok(old), _) => {
87                    let start = old.addr() - self.as_str().addr() - 1;
88
89                    self.0.replace_substr(old, new.as_str());
90
91                    let _ = self.resolve_range(start .. start + 1 + new.len());
92
93                    true
94                },
95
96                (Err(0), 0..) => self.push   (new),
97                (Err(0), ..0) => self.prepend(new),
98
99                (Err(_), _) => Err(InsertNotFound)?,
100            },
101            None => match self.iter_strs().neg_nth(index) {
102                Some(temp) => {
103                    if temp.len() + 1 == self.len() {
104                        Err(CantBeEmpty)?;
105                    }
106
107                    let range = self.0.my_substr_range(temp);
108
109                    self.0.replace_range(range.start - 1 .. range.end, "");
110
111                    true
112                },
113                None => false
114            }
115        })
116    }
117
118    /// Set the range of segments.
119    /// # Errors
120    /// If [`Self::range_str`] returns [`None`], returns the error [`RangeNotFound`].
121    ///
122    /// If `value` is [`None`] and `range` contains all segments, returns the error [`CantBeEmpty`].
123    /// # Examples
124    /// ```
125    /// use better_url::prelude::*;
126    ///
127    /// let mut path = FilePath::new("/c:/abc/def/ghi");
128    ///
129    /// path.set_range(1..2, Some(".././123/.")).unwrap(); assert_eq!(path, "/c:/123/def/ghi");
130    /// ```
131    pub fn set_range<'a, T: Into<FilePathSegments<'a>>, B: RangeBounds<isize>>(&mut self, range: B, value: Option<T>) -> Result<bool, SetPathError> {
132        Ok(match value.map(Into::into) {
133            Some(new) => {
134                let old = self.range_str(range).ok_or(RangeNotFound)?;
135
136                let start = old.addr() - self.as_str().addr() - 1;
137
138                self.0.replace_substr(old, new.as_str());
139
140                let _ = self.resolve_range(start .. start + 1 + new.len());
141
142                true
143            },
144            None => {
145                let old = self.range_str(range).ok_or(RangeNotFound)?;
146
147                if old.len() + 1 == self.len() {
148                    Err(CantBeEmpty)?;
149                }
150
151                let Range {start, end} = self.0.my_substr_range(old);
152
153                self.0.replace_range(start - 1 .. end, "");
154
155                true
156            }
157        })
158    }
159
160    /// Insert a new `index`th segment.
161    /// # Errors
162    /// If the insert isn't found, returns the error [`InsertNotFound`].
163    /// # Examples
164    /// ```
165    /// use better_url::prelude::*;
166    ///
167    /// let mut path = FilePath::new("/c:/abc/def/ghi");
168    ///
169    /// path.insert( 2, "123").unwrap(); assert_eq!(path, "/c:/abc/123/def/ghi");
170    /// path.insert( 3, ".." ).unwrap(); assert_eq!(path, "/c:/abc/def/ghi"    );
171    /// path.insert(-1, "123").unwrap(); assert_eq!(path, "/c:/abc/def/ghi/123");
172    /// ```
173    pub fn insert<'a, T: Into<FilePathSegment<'a>>>(&mut self, index: isize, value: T) -> Result<bool, SetPathError> {
174        let new = value.into();
175
176        let i = match (self.iter_strs().try_neg_nth(index), index) {
177            (Ok (x), ..0) => x.end_addr() - self.0.addr(),
178            (Ok (x), 0..) => x.    addr() - self.0.addr() - 1,
179            (Err(0), 0..) => self.len(),
180            (Err(0), ..0) => 0,
181            (Err(_), _  ) => Err(InsertNotFound)?
182        };
183
184        self.0.insert_with(i, ["/", new.as_str()]);
185
186        let _ = self.resolve_range(i .. i + 1 + new.len());
187
188        Ok(true)
189    }
190}