Skip to main content

moq_net/path/
parts.rs

1//! The one walk that splits a broadcast path into segments.
2//!
3//! A `\` escapes the `\` or `/` after it, so a segment is the text between two `/` that no
4//! escape covers: `a\/b` is one segment holding a `/`. Segments are yielded as written, escapes
5//! included; [`unescape`] reads one's content.
6
7use std::borrow::Cow;
8
9/// The segments of `path`, split only at a `/` no escape covers and still escaped as written.
10///
11/// The empty path has none. Anything else yields one more segment than it has separators,
12/// empty ones included, so a caller that requires non-empty segments checks them itself.
13///
14/// ```
15/// let parts: Vec<_> = moq_net::path::parts(r"room/a\/b/cam").collect();
16/// assert_eq!(parts, ["room", r"a\/b", "cam"]);
17/// assert_eq!(moq_net::path::parts("").count(), 0);
18/// ```
19pub fn parts(path: &str) -> Parts<'_> {
20	Parts {
21		rest: (!path.is_empty()).then_some(path),
22	}
23}
24
25/// The iterator [`parts`] returns, walking from either end.
26#[derive(Clone, Debug)]
27pub struct Parts<'a> {
28	rest: Option<&'a str>,
29}
30
31// Whether the `/` at `at` is escaped: an odd run of `\` before it. `/` and `\` are ASCII, so
32// the bytes before a separator never sit inside a multi-byte character. A path without `\`
33// pays one byte compare per separator.
34fn escaped(bytes: &[u8], at: usize) -> bool {
35	bytes[..at].iter().rev().take_while(|&&b| b == b'\\').count() % 2 == 1
36}
37
38impl<'a> Iterator for Parts<'a> {
39	type Item = &'a str;
40
41	fn next(&mut self) -> Option<&'a str> {
42		let s = self.rest?;
43		let bytes = s.as_bytes();
44		let mut from = 0;
45		while let Some(i) = s[from..].find('/') {
46			let at = from + i;
47			if !escaped(bytes, at) {
48				self.rest = Some(&s[at + 1..]);
49				return Some(&s[..at]);
50			}
51			from = at + 1;
52		}
53		self.rest = None;
54		Some(s)
55	}
56}
57
58impl DoubleEndedIterator for Parts<'_> {
59	fn next_back(&mut self) -> Option<Self::Item> {
60		let s = self.rest?;
61		let bytes = s.as_bytes();
62		let mut to = s.len();
63		while let Some(at) = s[..to].rfind('/') {
64			if !escaped(bytes, at) {
65				self.rest = Some(&s[..at]);
66				return Some(&s[at + 1..]);
67			}
68			to = at;
69		}
70		self.rest = None;
71		Some(s)
72	}
73}
74
75impl std::iter::FusedIterator for Parts<'_> {}
76
77/// A segment's content: each escaped `\` or `/` as the byte itself.
78///
79/// Borrows a segment with no escape. Expects a segment as [`parts`] yields it from a valid
80/// path, where every `\` escapes the byte after it.
81///
82/// ```
83/// assert_eq!(moq_net::path::unescape(r"a\/b\\c"), r"a/b\c");
84/// assert_eq!(moq_net::path::unescape("plain"), "plain");
85/// ```
86pub fn unescape(segment: &str) -> Cow<'_, str> {
87	if !segment.contains('\\') {
88		return Cow::Borrowed(segment);
89	}
90	let mut out = String::with_capacity(segment.len());
91	let mut chars = segment.chars();
92	while let Some(c) = chars.next() {
93		match c {
94			'\\' => out.extend(chars.next()),
95			c => out.push(c),
96		}
97	}
98	Cow::Owned(out)
99}
100
101/// The segment holding `content`: each `\` or `/` escaped by a `\`. The inverse of [`unescape`].
102///
103/// Borrows content with neither.
104///
105/// ```
106/// assert_eq!(moq_net::path::escape(r"a/b\c"), r"a\/b\\c");
107/// ```
108pub fn escape(content: &str) -> Cow<'_, str> {
109	if !content.contains(['\\', '/']) {
110		return Cow::Borrowed(content);
111	}
112	let mut out = String::with_capacity(content.len() + 2);
113	for c in content.chars() {
114		if matches!(c, '\\' | '/') {
115			out.push('\\');
116		}
117		out.push(c);
118	}
119	Cow::Owned(out)
120}
121
122/// Whether `segment` is one escaped segment: every `\` escapes a `\` or `/`, and no `/` is bare.
123pub(crate) fn is_segment(segment: &str) -> bool {
124	let mut bytes = segment.bytes();
125	while let Some(b) = bytes.next() {
126		match b {
127			b'\\' if matches!(bytes.next(), Some(b'\\' | b'/')) => {}
128			b'\\' | b'/' => return false,
129			_ => {}
130		}
131	}
132	true
133}
134
135#[cfg(test)]
136mod tests {
137	use super::*;
138
139	#[test]
140	fn splits_only_at_unescaped_separators() {
141		for (path, want) in [
142			("", &[][..]),
143			("a", &["a"]),
144			("a/b/c", &["a", "b", "c"]),
145			(r"a\/b", &[r"a\/b"]),
146			(r"a\\/b", &[r"a\\", "b"]),
147			(r"a\\\/b", &[r"a\\\/b"]),
148			(r"\/", &[r"\/"]),
149			(r"\//\/", &[r"\/", r"\/"]),
150			(r"x\/\/y/z\\", &[r"x\/\/y", r"z\\"]),
151			// Empty segments are yielded, not dropped: validation is the caller's.
152			("/a//b/", &["", "a", "", "b", ""]),
153		] {
154			let forward: Vec<_> = parts(path).collect();
155			assert_eq!(forward, want, "{path:?}");
156			let mut backward: Vec<_> = parts(path).rev().collect();
157			backward.reverse();
158			assert_eq!(backward, want, "{path:?} from the back");
159		}
160	}
161
162	#[test]
163	fn walks_from_both_ends_at_once() {
164		let mut walk = parts(r"a/b\/c/d/e");
165		assert_eq!(walk.next(), Some("a"));
166		assert_eq!(walk.next_back(), Some("e"));
167		assert_eq!(walk.next(), Some(r"b\/c"));
168		assert_eq!(walk.next_back(), Some("d"));
169		assert_eq!(walk.next(), None);
170		assert_eq!(walk.next_back(), None);
171	}
172
173	#[test]
174	fn rejoining_the_parts_gives_back_the_path() {
175		let mut texts = vec![String::new()];
176		for _ in 0..8 {
177			texts = texts
178				.iter()
179				.flat_map(|text| ['a', '/', '\\'].map(|c| format!("{text}{c}")))
180				.collect();
181			for text in &texts {
182				let joined = parts(text).collect::<Vec<_>>().join("/");
183				assert_eq!(&joined, text);
184			}
185		}
186	}
187
188	#[test]
189	fn unescapes_content() {
190		assert_eq!(unescape(r"\\"), r"\");
191		assert_eq!(unescape(r"\/"), "/");
192		assert_eq!(unescape("caf\u{e9}\\/\\\\x"), "caf\u{e9}/\\x");
193		assert!(matches!(unescape("plain"), Cow::Borrowed("plain")));
194		assert!(matches!(escape("plain"), Cow::Borrowed("plain")));
195		for content in ["", "/", r"\", r"a/\b", r"\\//", "caf\u{e9}/"] {
196			let segment = escape(content);
197			assert!(is_segment(&segment), "{segment:?}");
198			assert_eq!(parts(&segment).count(), usize::from(!content.is_empty()));
199			assert_eq!(unescape(&segment), content);
200		}
201	}
202
203	#[test]
204	fn recognizes_escaped_segments() {
205		for good in ["a", r"a\/b", r"\\", r"\/", r"a\\\/b", "*"] {
206			assert!(is_segment(good), "{good:?}");
207		}
208		for bad in ["a/b", r"a\", r"a\b", r"\*", "/", r"a\\\"] {
209			assert!(!is_segment(bad), "{bad:?}");
210		}
211	}
212}