1use std::fmt;
8
9use crate::{InStream, OutStream, SystemException};
10
11#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
13pub struct NameComponent {
14 pub id: String,
16 pub kind: String,
18}
19
20impl NameComponent {
21 pub fn new(id: impl Into<String>, kind: impl Into<String>) -> NameComponent {
23 NameComponent {
24 id: id.into(),
25 kind: kind.into(),
26 }
27 }
28
29 pub fn write(&self, out: &mut OutStream<'_>) -> Result<(), SystemException> {
31 out.write_string(&self.id)?;
32 out.write_string(&self.kind)
33 }
34
35 pub fn read(input: &mut InStream<'_>) -> Result<NameComponent, SystemException> {
37 Ok(NameComponent {
38 id: input.read_string()?,
39 kind: input.read_string()?,
40 })
41 }
42}
43
44pub type Name = Vec<NameComponent>;
46
47pub fn write_name(out: &mut OutStream<'_>, name: &[NameComponent]) -> Result<(), SystemException> {
49 out.write_len(name.len())?;
50 for component in name {
51 component.write(out)?;
52 }
53 Ok(())
54}
55
56pub fn read_name(input: &mut InStream<'_>) -> Result<Name, SystemException> {
58 let len = input.read_len(8).map_err(crate::stream::marshal)?;
60 (0..len).map(|_| NameComponent::read(input)).collect()
61}
62
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub struct InvalidName;
67
68impl fmt::Display for InvalidName {
69 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70 f.write_str("invalid name")
71 }
72}
73
74impl std::error::Error for InvalidName {}
75
76pub fn to_name(s: &str) -> Result<Name, InvalidName> {
86 if s.is_empty() {
87 return Err(InvalidName);
88 }
89 let mut name = Vec::new();
90 let mut id = String::new();
91 let mut kind = String::new();
92 let mut in_kind = false;
94 let mut seen = false;
95 let mut chars = s.chars();
96 while let Some(c) = chars.next() {
97 match c {
98 '\\' => {
99 let escaped = chars.next().ok_or(InvalidName)?;
100 if in_kind { &mut kind } else { &mut id }.push(escaped);
101 seen = true;
102 }
103 '/' => {
104 if !seen || trailing_dot(in_kind, &id, &kind) {
105 return Err(InvalidName);
106 }
107 name.push(NameComponent::new(
108 std::mem::take(&mut id),
109 std::mem::take(&mut kind),
110 ));
111 in_kind = false;
112 seen = false;
113 }
114 '.' => {
115 if in_kind {
116 return Err(InvalidName);
117 }
118 in_kind = true;
119 seen = true;
120 }
121 c => {
122 if in_kind { &mut kind } else { &mut id }.push(c);
123 seen = true;
124 }
125 }
126 }
127 if !seen || trailing_dot(in_kind, &id, &kind) {
128 return Err(InvalidName);
129 }
130 name.push(NameComponent::new(id, kind));
131 Ok(name)
132}
133
134fn trailing_dot(in_kind: bool, id: &str, kind: &str) -> bool {
137 in_kind && kind.is_empty() && !id.is_empty()
138}
139
140pub fn to_string(name: &[NameComponent]) -> Result<String, InvalidName> {
143 if name.is_empty() {
144 return Err(InvalidName);
145 }
146 let mut s = String::new();
147 for (i, component) in name.iter().enumerate() {
148 if i > 0 {
149 s.push('/');
150 }
151 if component.id.is_empty() && component.kind.is_empty() {
152 s.push('.');
153 continue;
154 }
155 escape_into(&mut s, &component.id);
156 if !component.kind.is_empty() {
157 s.push('.');
158 escape_into(&mut s, &component.kind);
159 }
160 }
161 Ok(s)
162}
163
164fn escape_into(s: &mut String, part: &str) {
165 for c in part.chars() {
166 if matches!(c, '/' | '.' | '\\') {
167 s.push('\\');
168 }
169 s.push(c);
170 }
171}
172
173#[cfg(test)]
174mod tests {
175 use super::*;
176
177 fn nc(id: &str, kind: &str) -> NameComponent {
178 NameComponent::new(id, kind)
179 }
180
181 #[test]
182 fn parses_components_and_escapes() {
183 assert_eq!(
184 to_name("a.b/c\\/d/.e").unwrap(),
185 vec![nc("a", "b"), nc("c/d", ""), nc("", "e")]
186 );
187 assert_eq!(to_name("x").unwrap(), vec![nc("x", "")]);
188 assert_eq!(to_name(".").unwrap(), vec![nc("", "")]);
189 assert_eq!(to_name("a\\.b.c").unwrap(), vec![nc("a.b", "c")]);
190 assert_eq!(to_name("a\\\\b").unwrap(), vec![nc("a\\b", "")]);
191 }
192
193 #[test]
194 fn rejects_malformed_names() {
195 for s in ["", "a//b", "/a", "a/", "a.b.c", "a.", "a./b", "a\\"] {
196 assert_eq!(to_name(s), Err(InvalidName), "{s:?}");
197 }
198 }
199
200 #[test]
201 fn writes_and_reads_back() {
202 let name = vec![
203 nc("a", "b"),
204 nc("c/d", ""),
205 nc("", "e"),
206 nc("", ""),
207 nc("x.y", "z\\"),
208 ];
209 let s = to_string(&name).unwrap();
210 assert_eq!(s, "a.b/c\\/d/.e/./x\\.y.z\\\\");
211 assert_eq!(to_name(&s).unwrap(), name);
212 assert_eq!(to_string(&[]), Err(InvalidName));
213 }
214}