Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/blob/main/vendor/uefi/src/fs/path/path.rs # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienux / vendor / uefi / src / fs / path / path.rs` 325 lines ยท 9674 bytes Raw Blame History 1 // SPDX-License-Identifier: MIT OR Apache-2.0 2 3 // allow "path.rs" in "path" 4 #![allow(clippy::module_inception)] 5 6 use crate::fs::path::{PathBuf, SEPARATOR}; 7 use crate::{CStr16, CString16, Char16}; 8 use core::fmt::{self, Display, Formatter}; 9 use core::ptr; 10 11 /// A path similar to the `Path` of the standard library, but based on 12 /// [`CStr16`] strings and [`SEPARATOR`] as separator. 13 /// 14 /// [`SEPARATOR`]: super::SEPARATOR 15 #[derive(Debug, Eq, PartialOrd, Ord)] 16 pub struct Path(CStr16); 17 18 impl Path { 19 /// Constructor. 20 #[must_use] 21 pub fn new + ?Sized>(s: &S) -> &Self { 22 // SAFETY: The handle is known to point to live storage here. 23 unsafe { &*(ptr::from_ref(s.as_ref()) as *const Self) } 24 } 25 26 /// Returns the underlying string. 27 #[must_use] 28 pub const fn to_cstr16(&self) -> &CStr16 { 29 &self.0 30 } 31 32 /// Returns a path buf from that type. 33 #[must_use] 34 pub fn to_path_buf(&self) -> PathBuf { 35 let cstring = CString16::from(&self.0); 36 PathBuf::from(cstring) 37 } 38 39 /// Iterator over the components of a path. 40 #[must_use] 41 pub fn components(&self) -> Components<'_> { 42 Components { 43 path: self.as_ref(), 44 i: 0, 45 } 46 } 47 48 /// Returns the parent directory as [`PathBuf`]. 49 /// 50 /// If the path is a top-level component, this returns None. 51 #[must_use] 52 pub fn parent(&self) -> Option { 53 let components_count = self.components().count(); 54 if components_count == 0 { 55 return None; 56 } 57 58 // Return None, as we do not treat "\\" as dedicated component. 59 let sep_count = self 60 .0 61 .as_slice() 62 .iter() 63 .filter(|char| **char == SEPARATOR) 64 .count(); 65 if sep_count == 0 { 66 return None; 67 } 68 69 let path = 70 self.components() 71 .take(components_count - 1) 72 .fold(CString16::new(), |mut acc, next| { 73 // Add separator, as needed. 74 if !acc.is_empty() && *acc.as_slice().last().unwrap() != SEPARATOR { 75 acc.push(SEPARATOR); 76 } 77 acc.extend(next); 78 acc 79 }); 80 let path = PathBuf::from(path); 81 Some(path) 82 } 83 84 /// Returns whether the path is empty. 85 #[must_use] 86 pub const fn is_empty(&self) -> bool { 87 self.to_cstr16().is_empty() 88 } 89 90 /// Creates an owned [`PathBuf`] with `path` adjoined to `self`. 91 #[must_use] 92 pub fn join>(&self, path: P) -> PathBuf { 93 let mut buf = self.to_path_buf(); 94 buf.push(path); 95 buf 96 } 97 } 98 99 impl Display for Path { 100 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 101 Display::fmt(self.to_cstr16(), f) 102 } 103 } 104 105 impl PartialEq for Path { 106 fn eq(&self, other: &Self) -> bool { 107 self.components().count() == other.components().count() 108 && !self 109 .components() 110 .zip(other.components()) 111 .any(|(c1, c2)| c1 != c2) 112 } 113 } 114 115 /// Iterator over the components of a path. For example, the path `\\a\\b\\c` 116 /// has the components `[a, b, c]`. This is a more basic approach than the 117 /// components type of the standard library. 118 #[derive(Debug)] 119 pub struct Components<'a> { 120 path: &'a CStr16, 121 i: usize, 122 } 123 124 impl<'a> Iterator for Components<'a> { 125 type Item = &'a [Char16]; 126 127 fn next(&mut self) -> Option { 128 if self.path.is_empty() { 129 return None; 130 } 131 if self.path.num_chars() == 1 && self.path.as_slice()[0] == SEPARATOR { 132 // The current implementation does not handle the root dir as 133 // dedicated component so far. We just return nothing. 134 return None; 135 } 136 137 // If the path is not empty and starts with a separator, skip it. 138 if self.i == 0 && *self.path.as_slice().first().unwrap() == SEPARATOR { 139 self.i = 1; 140 } 141 142 // Count how many characters are there until the next separator is 143 // found. 144 let len = self 145 .path 146 .iter() 147 .skip(self.i) 148 .take_while(|c| **c != SEPARATOR) 149 .count(); 150 151 let progress = self.i + len; 152 if progress > self.path.num_chars() { 153 None 154 } else { 155 // select the next component and build an owned string 156 let part = &self.path.as_slice()[self.i..self.i + len]; 157 158 // +1: skip the separator 159 self.i = progress + 1; 160 Some(part) 161 } 162 } 163 } 164 165 mod convenience_impls { 166 use super::*; 167 use core::borrow::Borrow; 168 169 impl AsRef for &Path { 170 fn as_ref(&self) -> &Path { 171 self 172 } 173 } 174 175 impl<'a> From<&'a CStr16> for &'a Path { 176 fn from(value: &'a CStr16) -> Self { 177 Path::new(value) 178 } 179 } 180 181 impl AsRef for Path { 182 fn as_ref(&self) -> &CStr16 { 183 &self.0 184 } 185 } 186 187 impl Borrow for Path { 188 fn borrow(&self) -> &CStr16 { 189 &self.0 190 } 191 } 192 193 impl AsRef for CStr16 { 194 fn as_ref(&self) -> &Path { 195 Path::new(self) 196 } 197 } 198 199 impl Borrow for CStr16 { 200 fn borrow(&self) -> &Path { 201 Path::new(self) 202 } 203 } 204 } 205 206 #[cfg(test)] 207 mod tests { 208 use super::*; 209 use crate::cstr16; 210 use alloc::vec::Vec; 211 212 #[test] 213 fn from_cstr16() { 214 let source: &CStr16 = cstr16!("\\hello\\foo\\bar"); 215 let _path: &Path = source.into(); 216 let _path: &Path = Path::new(source); 217 } 218 219 #[test] 220 fn from_cstring16() { 221 let source = CString16::try_from("\\hello\\foo\\bar").unwrap(); 222 let _path: &Path = source.as_ref().into(); 223 let _path: &Path = Path::new(source.as_ref()); 224 } 225 226 #[test] 227 fn components_iter() { 228 let path = Path::new(cstr16!("foo\\bar\\hello")); 229 let components = path.components().collect::>(); 230 let components: Vec<&[Char16]> = components.iter().map(|x| x.as_ref()).collect::>(); 231 let expected: &[&[Char16]] = &[ 232 cstr16!("foo").as_slice(), 233 cstr16!("bar").as_slice(), 234 cstr16!("hello").as_slice(), 235 ]; 236 assert_eq!(components.as_slice(), expected); 237 238 // In case there is a leading slash, it should be ignored. 239 let path = Path::new(cstr16!("\\foo\\bar\\hello")); 240 let components = path.components().collect::>(); 241 let components: Vec<&[Char16]> = components.iter().map(|x| x.as_ref()).collect::>(); 242 let expected: &[&[Char16]] = &[ 243 cstr16!("foo").as_slice(), 244 cstr16!("bar").as_slice(), 245 cstr16!("hello").as_slice(), 246 ]; 247 assert_eq!(components.as_slice(), expected); 248 249 // empty path iteration should be just fine 250 let empty_cstring16 = CString16::try_from("").unwrap(); 251 let path = Path::new(empty_cstring16.as_ref()); 252 let components = path.components().collect::>(); 253 let expected: &[&[Char16]] = &[]; 254 assert_eq!(components.as_slice(), expected); 255 256 // test empty path 257 let _path = Path::new(cstr16!()); 258 let path = Path::new(cstr16!("")); 259 let components = path.components().collect::>(); 260 let components: Vec<&[Char16]> = components.iter().map(|x| x.as_ref()).collect::>(); 261 let expected: &[&[Char16]] = &[]; 262 assert_eq!(components.as_slice(), expected); 263 264 // test path that has only root component. Treated as empty path by 265 // the components iterator. 266 let path = Path::new(cstr16!("\\")); 267 let components = path.components().collect::>(); 268 let components: Vec<&[Char16]> = components.iter().map(|x| x.as_ref()).collect::>(); 269 let expected: &[&[Char16]] = &[]; 270 assert_eq!(components.as_slice(), expected); 271 } 272 273 #[test] 274 fn test_parent() { 275 assert_eq!(None, Path::new(cstr16!("")).parent()); 276 assert_eq!(None, Path::new(cstr16!("\\")).parent()); 277 assert_eq!( 278 Path::new(cstr16!("a\\b")).parent(), 279 Some(PathBuf::from(cstr16!("a"))), 280 ); 281 assert_eq!( 282 Path::new(cstr16!("\\a\\b")).parent(), 283 Some(PathBuf::from(cstr16!("a"))), 284 ); 285 assert_eq!( 286 Path::new(cstr16!("a\\b\\c\\d")).parent(), 287 Some(PathBuf::from(cstr16!("a\\b\\c"))), 288 ); 289 assert_eq!(Path::new(cstr16!("abc")).parent(), None,); 290 } 291 292 #[test] 293 fn partial_eq() { 294 let path1 = Path::new(cstr16!(r"a\b")); 295 let path2 = Path::new(cstr16!(r"\a\b")); 296 let path3 = Path::new(cstr16!(r"a\b\c")); 297 298 assert_eq!(path1, path1); 299 assert_eq!(path2, path2); 300 assert_eq!(path3, path3); 301 302 // Equal as currently, we only support absolute paths, so the leading 303 // separator is obligatory. 304 assert_eq!(path1, path2); 305 assert_eq!(path2, path1); 306 307 assert_ne!(path1, path3); 308 assert_ne!(path3, path1); 309 } 310 311 #[test] 312 fn join() { 313 let path1 = Path::new(cstr16!(r"a\b")); 314 let path2 = Path::new(cstr16!(r"c\d")); 315 let path3 = Path::new(cstr16!(r"a\b\c\d")); 316 317 assert_eq!(path1.join(path2), path3.to_path_buf()); 318 319 let pathbuf1 = path1.to_path_buf(); 320 let pathbuf2 = path2.to_path_buf(); 321 let pathbuf3 = path3.to_path_buf(); 322 323 assert_eq!(pathbuf1.join(pathbuf2), pathbuf3); 324 } 325 }