1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
use super::Path;
use std::fmt::Display;
use std::ops::Deref;
use std::str::FromStr;
use anyhow::anyhow;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialOrd, PartialEq, Serialize)]
pub struct Name(String);
impl Name {
pub fn join(self, name: Name) -> Path {
vec![self, name].into_iter().collect()
}
}
impl FromStr for Name {
type Err = anyhow::Error;
#[inline]
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.is_empty()
|| s.find(|c| !matches!(c, '0'..='9' | 'a'..='z' | 'A'..='Z' | '-' | '_' | '.'))
.is_some()
{
Err(anyhow!("invalid characters in entry name"))
} else {
Ok(Self(s.into()))
}
}
}
impl Display for Name {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl AsRef<str> for Name {
fn as_ref(&self) -> &str {
self
}
}
impl Deref for Name {
type Target = String;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn from_str() {
assert!("/".parse::<Name>().is_err());
assert!("/test".parse::<Name>().is_err());
assert!("test/".parse::<Name>().is_err());
assert_eq!("foo".parse::<Name>().unwrap(), Name("foo".into()));
assert_eq!("some.txt".parse::<Name>().unwrap(), Name("some.txt".into()));
assert_eq!(
"my_wasm.wasm".parse::<Name>().unwrap(),
Name("my_wasm.wasm".into())
);
assert_eq!(
"not.a.cor-Rec.t.eX.tens.si0n_".parse::<Name>().unwrap(),
Name("not.a.cor-Rec.t.eX.tens.si0n_".into())
);
}
}