interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / vendor / uefi / src / fs / path / validation.rs

85 lines · 2606 bytes Raw Blame History
1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! Path validation for the purpose of the [`fs`] module. This is decoupled from
4//! [`Path`] and [`PathBuf`], as the Rust standard library also does it this
5//! way. Instead, the FS implementation is responsible for that.
6//!
7//! [`PathBuf`]: super::PathBuf
8//! [`fs`]: crate::fs
9
10use super::Path;
11use crate::Char16;
12use crate::fs::CHARACTER_DENY_LIST;
13use core::error;
14use core::fmt::{self, Display, Formatter};
15
16/// Errors related to file paths.
17#[derive(Debug, Clone, Eq, PartialEq)]
18pub enum PathError {
19 /// The path is empty / points to nothing.
20 Empty,
21 /// A component of the path is empty, i.e., two separators without content
22 /// in between were found.
23 EmptyComponent,
24 /// There are illegal characters in the path.
25 IllegalChar(Char16),
26}
27
28impl Display for PathError {
29 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
30 match self {
31 Self::Empty => write!(f, "path is empty"),
32 Self::EmptyComponent => write!(f, "path contains an empty component"),
33 Self::IllegalChar(c) => {
34 write!(
35 f,
36 "path contains an illegal character (value {})",
37 u16::from(*c)
38 )
39 }
40 }
41 }
42}
43
44impl error::Error for PathError {}
45
46/// Validates a path for the needs of the [`fs`] module.
47///
48/// [`fs`]: crate::fs
49pub fn validate_path<P: AsRef<Path>>(path: P) -> Result<(), PathError> {
50 let path = path.as_ref();
51 if path.is_empty() {
52 return Err(PathError::Empty);
53 }
54 for component in path.components() {
55 if component.is_empty() {
56 return Err(PathError::EmptyComponent);
57 } else if let Some(char) = component.iter().find(|c| CHARACTER_DENY_LIST.contains(c)) {
58 return Err(PathError::IllegalChar(*char));
59 }
60 }
61 Ok(())
62}
63
64#[cfg(test)]
65mod tests {
66 use super::*;
67 use crate::fs::PathBuf;
68 use crate::{CString16, cstr16};
69
70 #[test]
71 fn test_validate_path() {
72 validate_path(cstr16!("hello\\foo\\bar")).unwrap();
73
74 let err = validate_path(cstr16!("hello\\f>oo\\bar")).unwrap_err();
75 assert_eq!(err, PathError::IllegalChar(CHARACTER_DENY_LIST[6]));
76
77 let err = validate_path(cstr16!("hello\\\\bar")).unwrap_err();
78 assert_eq!(err, PathError::EmptyComponent);
79
80 let empty_cstring16 = CString16::try_from("").unwrap();
81 let path = PathBuf::from(empty_cstring16);
82 let err = validate_path(path).unwrap_err();
83 assert_eq!(err, PathError::Empty)
84 }
85}