Skip to main content

gix_validate/
submodule.rs

1use bstr::{BStr, ByteSlice};
2
3///
4pub mod name {
5    /// The error used in [name()](super::name()).
6    #[derive(Debug)]
7    #[allow(missing_docs)]
8    #[non_exhaustive]
9    pub enum Error {
10        Empty,
11        ParentComponent,
12    }
13
14    impl std::fmt::Display for Error {
15        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
16            match self {
17                Error::Empty => write!(f, "Submodule names cannot be empty"),
18                Error::ParentComponent => write!(f, "Submodules names must not contains '..'"),
19            }
20        }
21    }
22
23    impl std::error::Error for Error {}
24}
25
26/// Return the original `name` if it is valid, or the respective error indicating what was wrong with it.
27pub fn name(name: &BStr) -> Result<&BStr, name::Error> {
28    if name.is_empty() {
29        return Err(name::Error::Empty);
30    }
31    for component in name.as_bytes().split(|b| *b == b'/' || *b == b'\\') {
32        if component == b".." {
33            return Err(name::Error::ParentComponent);
34        }
35    }
36    Ok(name)
37}