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    match name.find(b"..") {
32        Some(pos) => {
33            let &b = name.get(pos + 2).ok_or(name::Error::ParentComponent)?;
34            if b == b'/' || b == b'\\' {
35                Err(name::Error::ParentComponent)
36            } else {
37                Ok(name)
38            }
39        }
40        None => Ok(name),
41    }
42}