Skip to main content

moq_net/path/
prefix.rs

1use std::cmp::Ordering;
2use std::fmt;
3use std::str::FromStr;
4
5use super::Path;
6use super::parts::{is_segment, parts};
7
8/// Why a string is not a valid [`Prefix`].
9#[derive(Clone, Debug, PartialEq, Eq)]
10#[non_exhaustive]
11pub enum InvalidPrefix {
12	/// The text holds a `*`. A grant is a set of prefixes, each covering its whole subtree,
13	/// so it takes no wildcard: `foo` already covers what `foo/**` meant.
14	Wildcard(String),
15	/// A segment is empty: a leading, trailing, or doubled `/`.
16	EmptySegment,
17	/// A segment holds a bare `/` or a `\` that escapes neither `\` nor `/`.
18	InvalidSegment(String),
19	/// More than [`Path::MAX_PARTS`] segments.
20	TooManySegments,
21}
22
23impl fmt::Display for InvalidPrefix {
24	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25		match self {
26			Self::Wildcard(text) if text == "**" => {
27				write!(
28					f,
29					"`**` is a wildcard: grants are prefixes, and the empty prefix covers every path"
30				)
31			}
32			Self::Wildcard(text) => match text
33				.strip_suffix("/**")
34				.filter(|head| !head.is_empty() && !head.contains('*'))
35			{
36				Some(head) => write!(
37					f,
38					"`{text}` is a wildcard: grants are prefixes, and `{head}` covers `{head}` and every path beneath it"
39				),
40				None => write!(
41					f,
42					"`{text}` holds a wildcard: grants are prefixes, each covering one path and every path beneath it"
43				),
44			},
45			Self::EmptySegment => write!(f, "invalid prefix: empty path segment"),
46			Self::InvalidSegment(segment) => write!(f, "invalid prefix: invalid segment {segment:?}"),
47			Self::TooManySegments => write!(f, "invalid prefix: more than {} segments", Path::MAX_PARTS),
48		}
49	}
50}
51
52impl std::error::Error for InvalidPrefix {}
53
54/// One member of a grant: a path, covering itself and every path beneath it.
55///
56/// The empty prefix covers every path. A prefix is spelled like a path: `/`-separated
57/// segments, a `\` escaping the `\` or `/` after it, at most [`Path::MAX_PARTS`]
58/// segments, and no leading, trailing, or doubled `/`. It never holds a `*`: parsing one
59/// fails loudly with [`InvalidPrefix::Wildcard`], since a grant never names a wildcard.
60///
61/// Ordered segment by segment, so a prefix sorts right before every path beneath it.
62#[derive(Clone, Default, PartialEq, Eq, Hash)]
63pub struct Prefix {
64	text: String,
65}
66
67impl Prefix {
68	/// The empty prefix, covering every path.
69	pub fn all() -> Self {
70		Self::default()
71	}
72
73	/// The canonical text.
74	pub fn as_str(&self) -> &str {
75		&self.text
76	}
77
78	/// Whether this is the empty prefix, covering every path.
79	pub fn is_empty(&self) -> bool {
80		self.text.is_empty()
81	}
82
83	/// Whether `path` is this prefix or beneath it. The path is normalized like a broadcast
84	/// path (slashes trimmed and collapsed).
85	pub fn matches(&self, path: &str) -> bool {
86		beneath(path, &self.text)
87	}
88
89	/// Whether this prefix covers some path at or beneath `path`: one lies beneath the other.
90	/// The path is normalized like a broadcast path.
91	pub fn overlaps(&self, path: &str) -> bool {
92		beneath(path, &self.text) || beneath(&self.text, path)
93	}
94
95	/// This prefix placed beneath the path `root`, normalized like a broadcast path (slashes
96	/// trimmed and collapsed). Fails when `root` holds a wildcard or a malformed escape, or
97	/// the result has too many segments.
98	pub fn rooted(&self, root: &str) -> Result<Self, InvalidPrefix> {
99		let root: Prefix = normalize(root).parse()?;
100		match (root.is_empty(), self.is_empty()) {
101			(true, _) => Ok(self.clone()),
102			(false, true) => Ok(root),
103			(false, false) => {
104				if parts(&root.text).count() + parts(&self.text).count() > Path::MAX_PARTS {
105					return Err(InvalidPrefix::TooManySegments);
106				}
107				Ok(Self {
108					text: format!("{}/{}", root.text, self.text),
109				})
110			}
111		}
112	}
113
114	/// This prefix as seen from the path `root`, normalized like a broadcast path: the rest
115	/// beneath it, or the empty prefix when this one covers `root` already. `None` when they
116	/// share no path.
117	pub fn rebase(&self, root: &str) -> Option<Self> {
118		// Segment by segment, so a root ending inside an escape matches no segment.
119		let mut root = parts(root).filter(|part| !part.is_empty());
120		let mut mine = parts(&self.text);
121		let mut end = 0;
122		loop {
123			match (root.next(), mine.next()) {
124				// This prefix ends at or above the root, so it covers all of it.
125				(_, None) => return Some(Self::all()),
126				// The root ends above this prefix: the rest of it is what lies beneath.
127				(None, Some(_)) => {
128					return Some(Self {
129						text: self.text[end..].to_string(),
130					});
131				}
132				(Some(theirs), Some(ours)) if theirs == ours => end += ours.len() + 1,
133				(Some(_), Some(_)) => return None,
134			}
135		}
136	}
137
138	/// Whether `other` is this prefix or beneath it. Both are canonical and never end inside
139	/// an escape, so the byte after this one is a separator exactly when it is a `/`.
140	fn contains(&self, other: &Prefix) -> bool {
141		let (path, prefix) = (&other.text, &self.text);
142		path.starts_with(prefix.as_str())
143			&& (prefix.is_empty() || path.len() == prefix.len() || path.as_bytes()[prefix.len()] == b'/')
144	}
145}
146
147/// Whether `path` is `prefix` or beneath it, segment by segment with both normalized like a
148/// broadcast path, so neither has to be canonical.
149fn beneath(path: &str, prefix: &str) -> bool {
150	let mut path = segments(path);
151	segments(prefix).all(|segment| path.next() == Some(segment))
152}
153
154/// The segments of `path` normalized like a broadcast path: empty ones dropped.
155fn segments(path: &str) -> impl Iterator<Item = &str> {
156	parts(path).filter(|part| !part.is_empty())
157}
158
159/// `path` with its slashes trimmed and collapsed, as a broadcast path is normalized.
160fn normalize(path: &str) -> std::borrow::Cow<'_, str> {
161	if parts(path).all(|part| !part.is_empty()) {
162		return path.into();
163	}
164	segments(path).collect::<Vec<_>>().join("/").into()
165}
166
167/// Segment-by-segment order of two canonical paths.
168fn order(a: &str, b: &str) -> Ordering {
169	parts(a).cmp(parts(b))
170}
171
172impl Ord for Prefix {
173	fn cmp(&self, other: &Self) -> Ordering {
174		order(&self.text, &other.text)
175	}
176}
177
178impl PartialOrd for Prefix {
179	fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
180		Some(self.cmp(other))
181	}
182}
183
184impl FromStr for Prefix {
185	type Err = InvalidPrefix;
186
187	/// Parse a prefix's text. A `*` anywhere is refused before anything else, so a wildcard
188	/// written where a prefix belongs always says so. Slashes are not normalized: a
189	/// leading, trailing, or doubled `/` is an error, so a typo cannot silently widen a grant.
190	fn from_str(text: &str) -> Result<Self, InvalidPrefix> {
191		if text.contains('*') {
192			return Err(InvalidPrefix::Wildcard(text.to_string()));
193		}
194		// One past the limit is enough to refuse, without splitting a peer's megabytes of
195		// `a/a/...` first.
196		let mut count = 0;
197		for part in parts(text).take(Path::MAX_PARTS + 1) {
198			count += 1;
199			if part.is_empty() {
200				return Err(InvalidPrefix::EmptySegment);
201			}
202			if !is_segment(part) {
203				return Err(InvalidPrefix::InvalidSegment(part.to_string()));
204			}
205		}
206		if count > Path::MAX_PARTS {
207			return Err(InvalidPrefix::TooManySegments);
208		}
209		Ok(Self { text: text.to_string() })
210	}
211}
212
213impl TryFrom<&str> for Prefix {
214	type Error = InvalidPrefix;
215
216	fn try_from(text: &str) -> Result<Self, InvalidPrefix> {
217		text.parse()
218	}
219}
220
221impl TryFrom<String> for Prefix {
222	type Error = InvalidPrefix;
223
224	fn try_from(text: String) -> Result<Self, InvalidPrefix> {
225		text.parse()
226	}
227}
228
229impl fmt::Display for Prefix {
230	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
231		f.write_str(&self.text)
232	}
233}
234
235impl fmt::Debug for Prefix {
236	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
237		fmt::Debug::fmt(&self.text, f)
238	}
239}
240
241impl serde::Serialize for Prefix {
242	fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
243		serializer.serialize_str(&self.text)
244	}
245}
246
247impl<'de> serde::Deserialize<'de> for Prefix {
248	fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
249		let text = <std::borrow::Cow<'de, str>>::deserialize(deserializer)?;
250		text.parse().map_err(serde::de::Error::custom)
251	}
252}
253
254/// A grant: a set of prefixes, reduced so no member lies beneath another.
255///
256/// Order is canonical (see [`Prefix`]), so two sets covering the same paths compare equal.
257/// The empty set grants nothing; [`all`](Self::all) grants everything.
258///
259/// Every operation costs near-linear time in the members it reads: collecting sorts once
260/// and sweeps, and a query binary-searches each prefix above the path it asks about, of
261/// which there are at most [`Path::MAX_PARTS`] + 1. So a peer's grant costs
262/// O(n log n) to read, whatever its shape.
263#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
264pub struct Prefixes(Vec<Prefix>);
265
266impl Prefixes {
267	/// The empty set, which grants nothing.
268	pub fn new() -> Self {
269		Self::default()
270	}
271
272	/// The set of the empty prefix, which grants every path.
273	pub fn all() -> Self {
274		Self(vec![Prefix::all()])
275	}
276
277	/// Add a prefix, dropping the members beneath it. Returns `false` when a member already
278	/// covers it, leaving the set unchanged.
279	pub fn insert(&mut self, prefix: Prefix) -> bool {
280		if self.holds(&prefix) {
281			return false;
282		}
283		// Everything beneath the new member sorts right after where it goes.
284		let at = self.0.partition_point(|member| member < &prefix);
285		let end = at + self.0[at..].iter().take_while(|member| prefix.contains(member)).count();
286		self.0.splice(at..end, [prefix]);
287		true
288	}
289
290	/// Whether some member covers `path`, normalized like a broadcast path.
291	pub fn matches(&self, path: &str) -> bool {
292		!self.0.is_empty() && self.covering(&normalize(path)).is_some()
293	}
294
295	/// Whether some member covers `prefix`, which is canonical already.
296	fn holds(&self, prefix: &Prefix) -> bool {
297		self.covering(&prefix.text).is_some()
298	}
299
300	/// The member covering the normalized `path`, if any.
301	fn covering(&self, path: &str) -> Option<&Prefix> {
302		// Each prefix of the path at a segment boundary, the empty one first. No member is
303		// deeper than a prefix may be, so the ancestors past that depth are never searched.
304		let ancestors = std::iter::once(0).chain(parts(path).enumerate().scan(0, |end, (i, part)| {
305			*end += usize::from(i > 0) + part.len();
306			Some(*end)
307		}));
308		ancestors.take(Path::MAX_PARTS + 1).find_map(|end| {
309			let ancestor = &path[..end];
310			let index = self.0.binary_search_by(|member| order(&member.text, ancestor)).ok()?;
311			Some(&self.0[index])
312		})
313	}
314
315	/// Whether every member of `other` is covered here: `other` grants nothing this set
316	/// does not. The empty set is covered by anything.
317	pub fn covers(&self, other: &Self) -> bool {
318		other.0.iter().all(|prefix| self.holds(prefix))
319	}
320
321	/// Whether some member covers a path at or beneath `path`, normalized like a broadcast
322	/// path.
323	pub fn overlaps(&self, path: &str) -> bool {
324		if self.0.is_empty() {
325			return false;
326		}
327		let path = normalize(path);
328		let path = path.as_ref();
329		if self.covering(path).is_some() {
330			return true;
331		}
332		// Members beneath it sort right after it.
333		let at = self
334			.0
335			.partition_point(|member| order(&member.text, path) == Ordering::Less);
336		self.0.get(at).is_some_and(|member| beneath(&member.text, path))
337	}
338
339	/// The paths both sets grant. Each member of the result is a member of one side lying
340	/// within the other, so it never grows past both sets together.
341	pub fn intersect(&self, other: &Self) -> Self {
342		let ours = self.0.iter().filter(|prefix| other.holds(prefix));
343		let theirs = other.0.iter().filter(|prefix| self.holds(prefix));
344		ours.chain(theirs).cloned().collect()
345	}
346
347	/// Every member as seen from the path `root`; see [`Prefix::rebase`].
348	pub fn rebase(&self, root: &str) -> Self {
349		self.0.iter().filter_map(|prefix| prefix.rebase(root)).collect()
350	}
351
352	/// Every member placed beneath the path `root`; see [`Prefix::rooted`].
353	pub fn rooted(&self, root: &str) -> Result<Self, InvalidPrefix> {
354		self.0.iter().map(|prefix| prefix.rooted(root)).collect()
355	}
356
357	/// The members, in canonical order.
358	pub fn iter(&self) -> std::slice::Iter<'_, Prefix> {
359		self.0.iter()
360	}
361
362	/// The number of members.
363	pub fn len(&self) -> usize {
364		self.0.len()
365	}
366
367	/// Whether there are no members, so nothing is granted.
368	pub fn is_empty(&self) -> bool {
369		self.0.is_empty()
370	}
371}
372
373impl From<Prefix> for Prefixes {
374	fn from(prefix: Prefix) -> Self {
375		Self(vec![prefix])
376	}
377}
378
379impl FromIterator<Prefix> for Prefixes {
380	/// Reduce in one sort and one sweep: a member's subtree sorts right after it, so each
381	/// prefix is beneath a member kept already only if it is beneath the last one kept.
382	fn from_iter<I: IntoIterator<Item = Prefix>>(iter: I) -> Self {
383		let mut sorted: Vec<Prefix> = iter.into_iter().collect();
384		sorted.sort_unstable();
385		let mut kept: Vec<Prefix> = Vec::with_capacity(sorted.len());
386		for prefix in sorted {
387			if kept.last().is_none_or(|last| !last.contains(&prefix)) {
388				kept.push(prefix);
389			}
390		}
391		kept.shrink_to_fit();
392		Self(kept)
393	}
394}
395
396impl Extend<Prefix> for Prefixes {
397	/// Reduce the members and the new prefixes together, in one pass.
398	fn extend<I: IntoIterator<Item = Prefix>>(&mut self, iter: I) {
399		let members = std::mem::take(&mut self.0);
400		*self = members.into_iter().chain(iter).collect();
401	}
402}
403
404impl IntoIterator for Prefixes {
405	type Item = Prefix;
406	type IntoIter = std::vec::IntoIter<Prefix>;
407
408	fn into_iter(self) -> Self::IntoIter {
409		self.0.into_iter()
410	}
411}
412
413impl<'a> IntoIterator for &'a Prefixes {
414	type Item = &'a Prefix;
415	type IntoIter = std::slice::Iter<'a, Prefix>;
416
417	fn into_iter(self) -> Self::IntoIter {
418		self.0.iter()
419	}
420}
421
422impl serde::Serialize for Prefixes {
423	fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
424		serializer.collect_seq(self.iter())
425	}
426}
427
428impl<'de> serde::Deserialize<'de> for Prefixes {
429	/// Reads a list and reduces it, so a persisted grant is canonical after a round trip.
430	fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
431		Ok(Vec::<Prefix>::deserialize(deserializer)?.into_iter().collect())
432	}
433}
434
435#[cfg(test)]
436mod tests {
437	use super::*;
438
439	fn prefix(text: &str) -> Prefix {
440		text.parse().unwrap()
441	}
442
443	fn prefixes(texts: &[&str]) -> Prefixes {
444		texts.iter().map(|text| prefix(text)).collect()
445	}
446
447	#[test]
448	fn refuses_every_wildcard_loudly() {
449		for text in ["**", "*", "a/**", "a/*", "cam-*.hang", "a*", "*/chat", "**/a", r"a\*"] {
450			let err = text.parse::<Prefix>().unwrap_err();
451			assert_eq!(err, InvalidPrefix::Wildcard(text.to_string()), "{text}");
452		}
453		assert!(
454			InvalidPrefix::Wildcard("**".into())
455				.to_string()
456				.contains("empty prefix")
457		);
458		assert!(
459			InvalidPrefix::Wildcard("anon/**".into())
460				.to_string()
461				.contains("`anon` covers")
462		);
463		assert!(
464			InvalidPrefix::Wildcard("a/*/b".into())
465				.to_string()
466				.contains("holds a wildcard")
467		);
468	}
469
470	#[test]
471	fn refuses_what_is_not_a_path() {
472		for text in ["/a", "a/", "a//b", r"a\", r"a\b"] {
473			assert!(
474				matches!(
475					text.parse::<Prefix>(),
476					Err(InvalidPrefix::EmptySegment | InvalidPrefix::InvalidSegment(_))
477				),
478				"{text}"
479			);
480		}
481		let deep = ["a"; Path::MAX_PARTS + 1].join("/");
482		assert!(deep.parse::<Prefix>().is_err());
483		assert!(["a"; Path::MAX_PARTS].join("/").parse::<Prefix>().is_ok());
484		assert!(prefix("").is_empty());
485		assert_eq!(prefix(r"a\/b/c\\").as_str(), r"a\/b/c\\");
486	}
487
488	#[test]
489	fn covers_its_subtree_by_segment() {
490		let room = prefix("room");
491		assert!(room.matches("room"));
492		assert!(room.matches("room/alice"));
493		assert!(!room.matches("roomy"));
494		assert!(!room.matches("room-b/x"));
495		assert!(!room.matches(""));
496		assert!(Prefix::all().matches(""));
497		assert!(Prefix::all().matches("anything/at/all"));
498		// An escaped `/` never splits a segment.
499		assert!(!prefix("a").matches(r"a\/b"));
500		assert!(prefix(r"a\/b").matches(r"a\/b/c"));
501		assert!(prefix(r"a\\").matches(r"a\\/b"));
502		assert!(!prefix(r"a\/").matches(r"a\/b"));
503		assert!(prefix("room/a").overlaps("room"));
504		assert!(room.overlaps("room/a"));
505		assert!(!prefix("a").overlaps("b"));
506		// A path no prefix can spell still has an answer.
507		assert!(room.overlaps("room/cam-*"));
508	}
509
510	#[test]
511	fn sorts_a_subtree_right_after_its_prefix() {
512		let mut sorted = [prefix("a/b"), prefix("a-b"), prefix("a"), prefix("a/b/c"), prefix("")];
513		sorted.sort();
514		let texts: Vec<_> = sorted.iter().map(Prefix::as_str).collect();
515		assert_eq!(texts, ["", "a", "a/b", "a/b/c", "a-b"]);
516	}
517
518	#[test]
519	fn collecting_reduces_and_sorts() {
520		assert_eq!(prefixes(&["a/b", "a-b", "a", "c/d"]), prefixes(&["c/d", "a-b", "a"]));
521		assert_eq!(prefixes(&["a/b", "", "c"]), Prefixes::all());
522		assert_eq!(prefixes(&["b", "a", "a"]).len(), 2);
523		let set = prefixes(&["b", "a/x", "a-b"]);
524		let texts: Vec<_> = set.iter().map(Prefix::as_str).collect();
525		assert_eq!(texts, ["a/x", "a-b", "b"]);
526	}
527
528	#[test]
529	fn insert_drops_what_it_covers() {
530		let mut set = prefixes(&["a/b", "a/c", "a-b", "b"]);
531		assert!(!set.insert(prefix("a/b/x")));
532		assert!(set.insert(prefix("a")));
533		assert_eq!(set, prefixes(&["a", "a-b", "b"]));
534		assert!(set.insert(prefix("")));
535		assert_eq!(set, Prefixes::all());
536	}
537
538	#[test]
539	fn queries_any_member() {
540		let set = prefixes(&["a/b", "c"]);
541		assert!(set.matches("a/b/x"));
542		assert!(set.matches("c"));
543		assert!(!set.matches("a"));
544		assert!(!set.matches("a/bc"));
545		assert!(set.matches("c/d"));
546		assert!(set.overlaps("a"));
547		assert!(set.overlaps("a/b/c"));
548		assert!(set.overlaps(""));
549		assert!(!set.overlaps("a/c"));
550		assert!(!set.overlaps("b"));
551		assert!(Prefixes::all().overlaps("z"));
552		assert!(!Prefixes::new().matches(""));
553		assert!(!Prefixes::new().overlaps(""));
554	}
555
556	#[test]
557	fn covers_and_intersects() {
558		let wide = prefixes(&["a", "b/c"]);
559		assert!(wide.covers(&prefixes(&["a/x", "b/c/d"])));
560		assert!(!wide.covers(&prefixes(&["a/x", "b"])));
561		assert!(wide.covers(&Prefixes::new()));
562		assert!(!Prefixes::new().covers(&wide));
563		assert_eq!(wide.intersect(&prefixes(&["a/x", "b", "z"])), prefixes(&["a/x", "b/c"]));
564		assert_eq!(wide.intersect(&Prefixes::all()), wide);
565		assert!(wide.intersect(&prefixes(&["z"])).is_empty());
566	}
567
568	#[test]
569	fn rebases_and_roots() {
570		let set = prefixes(&["a/b", "c"]);
571		assert_eq!(set.rebase("a"), prefixes(&["b"]));
572		assert_eq!(set.rebase("c/d"), Prefixes::all());
573		assert_eq!(set.rebase(""), set);
574		assert!(set.rebase("x").is_empty());
575		assert_eq!(set.rooted("r").unwrap(), prefixes(&["r/a/b", "r/c"]));
576		assert_eq!(Prefixes::all().rooted("r").unwrap(), prefixes(&["r"]));
577		assert!(set.rooted("*").is_err());
578		let deep = ["a"; Path::MAX_PARTS].join("/");
579		assert!(set.rooted(&deep).is_err());
580		assert_eq!(set.rooted("r").unwrap().rebase("r"), set);
581		// A root is normalized like a broadcast path.
582		assert_eq!(set.rebase("/a//"), prefixes(&["b"]));
583		assert_eq!(set.rooted("/r//s/").unwrap(), prefixes(&["r/s/a/b", "r/s/c"]));
584		// A root ending inside an escape is no segment of a prefix.
585		let escaped = prefixes(&[r"a\/b"]);
586		assert!(escaped.rebase(r"a\").is_empty());
587		assert_eq!(escaped.rebase(r"a\/b"), Prefixes::all());
588	}
589
590	#[test]
591	fn serde_round_trips_reduced_and_refuses_wildcards() {
592		let set: Prefixes = serde_json::from_str(r#"["a/b", "a", "c"]"#).unwrap();
593		assert_eq!(serde_json::to_string(&set).unwrap(), r#"["a","c"]"#);
594		let err = serde_json::from_str::<Prefixes>(r#"["a/**"]"#).unwrap_err().to_string();
595		assert!(err.contains("`a` covers"), "{err}");
596	}
597
598	#[test]
599	fn normalizes_a_path_it_is_asked_about() {
600		let accent = prefix("é");
601		let set = prefixes(&["é", "a/ü"]);
602		for path in ["é", "/é", "é/", "//é//x", "é//x/"] {
603			assert!(accent.matches(path), "{path}");
604			assert!(set.matches(path), "{path}");
605			assert!(set.overlaps(path), "{path}");
606		}
607		for path in ["/a", "a/", "//a//"] {
608			assert!(!set.matches(path), "{path}");
609			assert!(set.overlaps(path), "{path}");
610			assert!(prefix("a/ü").overlaps(path), "{path}");
611		}
612		assert!(set.matches("/a//ü/"));
613		assert!(!set.matches("/éa"));
614		assert!(!set.overlaps("/ü"));
615		// Slashes collapse, but an escaped `/` still never splits a segment.
616		assert!(!prefix("a").matches(r"/a\/b"));
617		assert!(!prefix(r"a\/b").overlaps(r"a\"));
618		assert!(prefix(r"a\/b").overlaps(r"/a\/b//"));
619	}
620
621	/// Over every short path built from separators, escapes, and multi-byte characters, a
622	/// query never panics, answers as it does for the path normalized, and agrees with each
623	/// member alone.
624	#[test]
625	fn agrees_with_members_on_any_path() {
626		let pieces = ["", "/", "a", "é", r"\/", r"\\", r"\"];
627		let mut paths = vec![String::new()];
628		// Miri checks the shorter paths only: thousands of them take it past the test timeout.
629		for _ in 0..if cfg!(miri) { 2 } else { 4 } {
630			let longer: Vec<String> = paths
631				.iter()
632				.flat_map(|path| pieces.iter().map(move |piece| format!("{path}{piece}")))
633				.collect();
634			paths.extend(longer);
635		}
636		paths.sort();
637		paths.dedup();
638		let members = ["", "a", "é", "a/é", "é/a", r"a\/é", r"\\", "é/é"];
639		let sets: Vec<Prefixes> = (0..1u32 << members.len())
640			.step_by(7)
641			.map(|mask| {
642				(0..members.len())
643					.filter(|bit| mask & (1 << bit) != 0)
644					.map(|bit| prefix(members[bit]))
645					.collect()
646			})
647			.collect();
648		for path in &paths {
649			let normal = normalize(path);
650			for member in members.map(prefix) {
651				assert_eq!(member.matches(path), member.matches(&normal), "{member:?} {path}");
652				assert_eq!(member.overlaps(path), member.overlaps(&normal), "{member:?} {path}");
653			}
654			for set in &sets {
655				assert_eq!(
656					set.matches(path),
657					set.iter().any(|member| member.matches(path)),
658					"{set:?} {path}"
659				);
660				assert_eq!(
661					set.overlaps(path),
662					set.iter().any(|member| member.overlaps(path)),
663					"{set:?} {path}"
664				);
665			}
666		}
667	}
668
669	/// Every operation agrees with a brute-force reading over a small universe of paths.
670	#[test]
671	fn agrees_with_brute_force() {
672		let universe = ["", "a", "a/b", "a/b/c", "a/c", "a-b", "b", "b/a"];
673		let paths: Vec<&str> = universe.to_vec();
674		// Every subset of a few members; under Miri, a spread of them, since every pair is checked.
675		let members = ["", "a", "a/b", "a-b", "b/a"];
676		let sets: Vec<Prefixes> = (0..1u32 << members.len())
677			.step_by(if cfg!(miri) { 5 } else { 1 })
678			.map(|mask| {
679				(0..members.len())
680					.filter(|bit| mask & (1 << bit) != 0)
681					.map(|bit| prefix(members[bit]))
682					.collect()
683			})
684			.collect();
685		let covered =
686			|set: &Prefixes| -> Vec<&str> { paths.iter().copied().filter(|path| set.matches(path)).collect() };
687		let brute = |set: &Prefixes, path: &str| set.iter().any(|member| member.matches(path));
688		for a in &sets {
689			for path in &paths {
690				assert_eq!(a.matches(path), brute(a, path), "{a:?} {path}");
691				let p = prefix(path);
692				let beneath: Vec<_> = paths.iter().filter(|other| p.matches(other)).collect();
693				// Covering a path covers its whole subtree.
694				assert_eq!(
695					a.matches(path),
696					beneath.iter().all(|other| brute(a, other)),
697					"{a:?} covers {path}"
698				);
699				assert_eq!(
700					a.overlaps(path),
701					beneath.iter().any(|other| brute(a, other)),
702					"{a:?} overlaps {path}"
703				);
704			}
705			for b in &sets {
706				let both = a.intersect(b);
707				let want: Vec<&str> = paths
708					.iter()
709					.copied()
710					.filter(|path| brute(a, path) && brute(b, path))
711					.collect();
712				assert_eq!(covered(&both), want, "{a:?} & {b:?}");
713				let a_paths = covered(a);
714				assert_eq!(
715					a.covers(b),
716					covered(b).iter().all(|path| a_paths.contains(path)),
717					"{a:?} covers {b:?}"
718				);
719			}
720		}
721	}
722}