Skip to main content

moq_net/path/
mod.rs

1//! Broadcast paths and the prefixes that grant them.
2//!
3//! [`Path`] is a literal coordinate: `/`-separated non-empty segments, with
4//! segment-aware prefix operations. A `\` escapes the `\` or `/` after it, so `a\/b` is one
5//! segment holding a `/`; [`parts`] is the one walk every segment reading goes through.
6//! [`Prefixes`] is a grant or an origin scope: a set of [`Prefix`]es, each covering its
7//! whole subtree.
8
9mod parts;
10mod prefix;
11
12pub use parts::{Parts, escape, parts, unescape};
13pub use prefix::{InvalidPrefix, Prefix, Prefixes};
14
15use std::fmt::{self, Display};
16use std::sync::Arc;
17
18use crate::coding::{Decode, DecodeError, Decoder, Encode, EncodeError, Encoder};
19
20// Paths up to this many bytes live inline, in the word `Shared` holds beside its `Arc` less the
21// length and the tag: 22 bytes on 64-bit targets and 10 on 32-bit ones.
22const INLINE: usize = size_of::<Arc<str>>() + size_of::<usize>() - 2;
23
24/// Inline bytes, a static literal, or a suffix of a shared reference-counted buffer.
25///
26/// Short paths copy inline, so cloning one is a memcpy with no atomics. A long path shares
27/// one allocation: cloning bumps a refcount and suffix operations like `strip_prefix` only
28/// advance `start`, so one allocation serves every copy of a path as it fans out.
29#[derive(Clone)]
30enum Repr {
31	Inline { len: u8, buf: [u8; INLINE] },
32	Static(&'static str),
33	Shared { start: u16, buf: Arc<str> },
34}
35
36const _: () = assert!(size_of::<Repr>() == INLINE + 2);
37// Every path fits `MAX_BYTES`, so a `Shared` offset into one always fits its `u16`.
38const _: () = assert!(Path::MAX_BYTES <= u16::MAX as usize);
39
40impl Repr {
41	// A copy of a string already known to fit `MAX_BYTES`.
42	fn copy_bounded(s: &str) -> Self {
43		debug_assert!(s.len() <= Path::MAX_BYTES);
44		if s.len() <= INLINE {
45			let mut buf = [0; INLINE];
46			buf[..s.len()].copy_from_slice(s.as_bytes());
47			Repr::Inline {
48				len: s.len() as u8,
49				buf,
50			}
51		} else {
52			Repr::Shared {
53				start: 0,
54				buf: s.into(),
55			}
56		}
57	}
58}
59
60/// Why a string is not a valid [`Path`] or [`Relative`].
61#[derive(Debug, Copy, Clone, Eq, PartialEq, thiserror::Error)]
62#[non_exhaustive]
63pub enum Error {
64	/// Longer than [`Path::MAX_BYTES`].
65	#[error("path is longer than {} bytes", Path::MAX_BYTES)]
66	TooLong,
67
68	/// A leading, trailing, or doubled `/`, which would give one path several spellings.
69	#[error("path contains an empty segment")]
70	EmptySegment,
71
72	/// A `\` before anything but `\` or `/`, which would give one namespace field several spellings.
73	#[error(r"path contains a `\` that escapes neither `\` nor `/`")]
74	InvalidEscape,
75}
76
77// A path is refused rather than normalized, so each one has exactly one spelling.
78fn validate(s: &str) -> Result<(), Error> {
79	if s.len() > Path::MAX_BYTES {
80		return Err(Error::TooLong);
81	}
82	if s.is_empty() {
83		return Ok(());
84	}
85	// Without a `\`, every `/` separates, so the plain checks are the whole rule.
86	if !s.as_bytes().contains(&b'\\') {
87		return match s.starts_with('/') || s.ends_with('/') || s.contains("//") {
88			true => Err(Error::EmptySegment),
89			false => Ok(()),
90		};
91	}
92	// A `\` escapes the byte after it, which must be `\` or `/`: the IETF namespace mapping
93	// writes a field's `\` and `/` that way and nothing else, so any other spelling could not
94	// round-trip.
95	let mut rest = s.as_bytes();
96	while let Some(i) = rest.iter().position(|&b| b == b'\\') {
97		match rest.get(i + 1) {
98			Some(b'\\' | b'/') => rest = &rest[i + 2..],
99			_ => return Err(Error::InvalidEscape),
100		}
101	}
102	// TEMPORARY MIGRATION, delete at the next version cut: the previous release splits at every
103	// `/`, escaped or not, and trims and collapses the empty segments that leaves, so it would
104	// re-spell `a\//b` as `a\/b`, another broadcast's path. Refuse what it would re-spell.
105	if s.ends_with('/') || s.contains("//") {
106		return Err(Error::EmptySegment);
107	}
108	// An escaped `/` is content, so only a bare one can leave a segment empty.
109	match parts(s).any(str::is_empty) {
110		true => Err(Error::EmptySegment),
111		false => Ok(()),
112	}
113}
114
115/// A broadcast path that provides safe prefix matching operations.
116///
117/// This type wraps a string but provides path-aware operations that respect
118/// delimiter boundaries, preventing issues like "foo" matching "foobar".
119///
120/// A path is a key of non-empty segments joined by `/`, so it has one spelling:
121/// [`Path::new`] refuses a leading, trailing, or doubled `/` rather than collapsing it.
122/// A `\` escapes the `\` or `/` after it, which is how a moq-transport namespace field holding
123/// either one is spelled, and any other `\` is refused. An escaped `/` never splits a segment:
124/// `a\/b` is one segment, a prefix never ends inside it, and a pattern's `*` matches all of it.
125/// Until the previous release is gone, an escaped `/` still counts against [`Path::MAX_PARTS`],
126/// and one beside a bare `/` or at the end is refused, since that release splits at every `/`.
127/// A path is at most [`Path::MAX_BYTES`] long. The empty path has no segments; it is the
128/// origin's root and prefixes every other path. The same type names an exact broadcast
129/// and the prefix a route or announcement covers, so a broadcast's own path is the prefix
130/// it announces, and a prefix needs no trailing `/`. See [`Relative`] for `..`-style
131/// references.
132///
133/// Cloning is cheap: a short path is stored inline, and a long one shares a single
134/// reference-counted allocation that suffix operations like [`Path::strip_prefix`] reuse.
135///
136/// # Examples
137/// ```
138/// use moq_net::Path;
139///
140/// // An empty segment is refused, not collapsed.
141/// assert!(Path::new("/foo/bar/").is_err());
142/// assert!(Path::new("foo//bar").is_err());
143///
144/// let base = Path::new("api/v1")?;
145/// assert!(base.has_prefix(&Path::from_static("api")));
146/// assert!(base.has_prefix(&Path::empty()));
147///
148/// let joined = base.join(&Path::from_static("users"))?;
149/// assert_eq!(joined.as_str(), "api/v1/users");
150/// # Ok::<(), moq_net::path::Error>(())
151/// ```
152#[derive(Clone)]
153pub struct Path(Repr);
154
155impl Path {
156	/// Maximum number of segments in a path.
157	///
158	/// Matches the IETF moq-transport limit of 32 fields in a namespace tuple.
159	/// moq-lite enforces the same bound: encoding or decoding a deeper path fails,
160	/// and publishing one to an origin is rejected.
161	pub const MAX_PARTS: usize = 32;
162
163	/// Maximum length of a path in bytes.
164	///
165	/// Matches the IETF moq-transport limit of 4096 bytes for a namespace. Its tuple fields
166	/// drop the path's separators and escapes, so every path fits both wires.
167	pub const MAX_BYTES: usize = 4096;
168
169	/// Create a new Path by copying a string slice.
170	///
171	/// The empty string is the root path. Anything else must be non-empty segments joined
172	/// by `/`: a leading, trailing, or doubled `/` fails with [`Error::EmptySegment`], a `\`
173	/// before anything but `\` or `/` with [`Error::InvalidEscape`], and a string longer
174	/// than [`Path::MAX_BYTES`] with [`Error::TooLong`].
175	pub fn new(s: &str) -> Result<Self, Error> {
176		validate(s)?;
177		Ok(Self(Repr::copy_bounded(s)))
178	}
179
180	/// Create a new Path from a string literal without copying it, validated like [`Path::new`].
181	///
182	/// # Panics
183	///
184	/// If the literal is not a valid path.
185	pub fn from_static(s: &'static str) -> Self {
186		if let Err(err) = validate(s) {
187			panic!("invalid path literal {s:?}: {err}");
188		}
189		Self(Repr::Static(s))
190	}
191
192	// A copy of this path skipping the first `n` bytes, reusing the shared buffer when possible.
193	pub(crate) fn slice_from(&self, n: usize) -> Path {
194		let rest = &self.as_str()[n..];
195		match &self.0 {
196			Repr::Static(s) => Path(Repr::Static(&s[n..])),
197			Repr::Shared { buf, start } if rest.len() > INLINE => Path(Repr::Shared {
198				buf: buf.clone(),
199				// The offset stays within the buffer, which fits `MAX_BYTES` and so a `u16`.
200				start: *start + n as u16,
201			}),
202			_ => Path(Repr::copy_bounded(rest)),
203		}
204	}
205
206	/// Check if this path has the given prefix, respecting path boundaries.
207	///
208	/// Unlike String::starts_with, this ensures that "foo" does not match "foobar".
209	/// The prefix must either:
210	/// - Be exactly equal to this path
211	/// - Be followed by a '/' delimiter in the original path
212	/// - Be empty (matches everything)
213	///
214	/// # Examples
215	/// ```
216	/// use moq_net::Path;
217	///
218	/// let path = Path::from_static("foo/bar");
219	/// assert!(path.has_prefix(&Path::from_static("foo")));
220	/// assert!(!path.has_prefix(&Path::from_static("fo")));
221	///
222	/// let path = Path::from_static("foobar");
223	/// assert!(!path.has_prefix(&Path::from_static("foo")));
224	/// ```
225	pub fn has_prefix(&self, prefix: &Path) -> bool {
226		self.prefix_len(prefix).is_some()
227	}
228
229	// The bytes to skip past `prefix` and its delimiter, if it is a whole-segment prefix.
230	fn prefix_len(&self, prefix: &Path) -> Option<usize> {
231		let prefix = prefix.as_str();
232		if prefix.is_empty() {
233			return Some(0);
234		}
235
236		let s = self.as_str();
237		if !s.starts_with(prefix) {
238			return None;
239		}
240
241		// Check if the prefix is the exact match
242		if s.len() == prefix.len() {
243			return Some(s.len());
244		}
245
246		// Otherwise, ensure the character after the prefix is a delimiter
247		(s.as_bytes().get(prefix.len()) == Some(&b'/')).then_some(prefix.len() + 1)
248	}
249
250	/// The remainder after removing `prefix`, or `None` if it isn't a prefix.
251	///
252	/// Only whole segments match: `a/bc` is not prefixed by `a/b`. An empty prefix
253	/// returns the whole path.
254	pub fn strip_prefix(&self, prefix: &Path) -> Option<Path> {
255		let n = self.prefix_len(prefix)?;
256		Some(self.slice_from(n))
257	}
258
259	/// The first `n` segments, or `None` if the path has fewer.
260	///
261	/// # Examples
262	/// ```
263	/// use moq_net::Path;
264	///
265	/// let path = Path::from_static("foo/bar/baz");
266	/// assert_eq!(path.head(2), Some(Path::from_static("foo/bar")));
267	/// assert_eq!(path.head(0), Some(Path::empty()));
268	/// assert_eq!(path.head(4), None);
269	///
270	/// // An escaped `/` is inside a segment.
271	/// assert_eq!(Path::from_static(r"foo\/bar/baz").head(1), Some(Path::from_static(r"foo\/bar")));
272	/// ```
273	pub fn head(&self, n: usize) -> Option<Path> {
274		let end = self.head_len(n)?;
275		let s = self.as_str();
276		// A run of whole segments of a valid path is itself valid.
277		Some(match &self.0 {
278			Repr::Static(s) => Path(Repr::Static(&s[..end])),
279			_ => Path(Repr::copy_bounded(&s[..end])),
280		})
281	}
282
283	// The bytes the first `n` segments span, without the `/` after them, or `None` if the
284	// path has fewer.
285	pub(crate) fn head_len(&self, n: usize) -> Option<usize> {
286		let mut parts = self.parts();
287		let mut end = 0;
288		for i in 0..n {
289			end += parts.next()?.len() + usize::from(i > 0);
290		}
291		Some(end)
292	}
293
294	/// How deep the path counts against [`Path::MAX_PARTS`].
295	///
296	/// TEMPORARY MIGRATION, delete at the next version cut (and count [`Path::parts`] instead):
297	/// the previous release splits at every `/`, escaped or not, and its decoder refuses a
298	/// path past 32 parts by that count by ending the whole announce stream. So until it is
299	/// gone, the limit counts every `/`, which is never fewer than the segments.
300	pub(crate) fn depth(&self) -> usize {
301		self.as_str().split_terminator('/').count()
302	}
303
304	/// Iterate over the segments of the path, split only at a `/` no `\` escapes, each still
305	/// escaped as written. See [`unescape`] for a segment's content.
306	///
307	/// The empty path has no parts.
308	///
309	/// # Examples
310	/// ```
311	/// use moq_net::Path;
312	///
313	/// let path = Path::from_static(r"foo/bar\/baz");
314	/// assert_eq!(path.parts().collect::<Vec<_>>(), ["foo", r"bar\/baz"]);
315	/// assert_eq!(Path::empty().parts().count(), 0);
316	/// ```
317	pub fn parts(&self) -> Parts<'_> {
318		// The route table walks this on every lookup, so a path without `\` costs a byte
319		// compare per separator over a plain split.
320		parts(self.as_str())
321	}
322
323	/// Whether a segment starts with `.`, which hides the path from announce
324	/// discovery below the requested prefix.
325	pub(crate) fn is_hidden(&self) -> bool {
326		self.parts().any(|part| part.starts_with('.'))
327	}
328
329	/// The path as a string, with no leading or trailing slash.
330	pub fn as_str(&self) -> &str {
331		match &self.0 {
332			// SAFETY: `Repr::copy_bounded` and `concat` fill `buf[..len]` only from whole `&str`s
333			// and an ASCII `/`, so those bytes are valid UTF-8.
334			Repr::Inline { len, buf } => unsafe { std::str::from_utf8_unchecked(&buf[..*len as usize]) },
335			Repr::Static(s) => s,
336			Repr::Shared { buf, start } => &buf[*start as usize..],
337		}
338	}
339
340	/// The empty path, which prefixes every other path.
341	pub const fn empty() -> Path {
342		Path(Repr::Static(""))
343	}
344
345	/// Returns `true` if this is the empty path.
346	pub fn is_empty(&self) -> bool {
347		self.as_str().is_empty()
348	}
349
350	/// The length in bytes, not segments.
351	pub fn len(&self) -> usize {
352		self.as_str().len()
353	}
354
355	/// Join this path with another path component.
356	///
357	/// Fails if the result is longer than [`Path::MAX_BYTES`].
358	///
359	/// # Examples
360	/// ```
361	/// use moq_net::Path;
362	///
363	/// let base = Path::from_static("foo");
364	/// let joined = base.join(&Path::from_static("bar"))?;
365	/// assert_eq!(joined.as_str(), "foo/bar");
366	///
367	/// // The empty path is the identity.
368	/// assert_eq!(base.join(&Path::empty())?.as_str(), "foo");
369	/// # Ok::<(), moq_net::path::Error>(())
370	/// ```
371	pub fn join(&self, other: &Path) -> Result<Path, Error> {
372		if self.is_empty() {
373			Ok(other.clone())
374		} else if other.is_empty() {
375			Ok(self.clone())
376		} else {
377			Self::concat(self.as_str(), other.as_str())
378		}
379	}
380
381	// `join` where the result is known to fit, like a prefix and the suffix split from
382	// one path. Panics otherwise, since that breaks an internal invariant.
383	pub(crate) fn rejoin(&self, other: &Path) -> Path {
384		self.join(other).expect("a rejoined path fits")
385	}
386
387	// `a/b` for two non-empty valid paths, built in place.
388	pub(crate) fn concat(a: &str, b: &str) -> Result<Path, Error> {
389		let len = a.len() + 1 + b.len();
390		if len > Self::MAX_BYTES {
391			return Err(Error::TooLong);
392		}
393		if len <= INLINE {
394			let mut buf = [0; INLINE];
395			buf[..a.len()].copy_from_slice(a.as_bytes());
396			buf[a.len()] = b'/';
397			buf[a.len() + 1..len].copy_from_slice(b.as_bytes());
398			Ok(Path(Repr::Inline { len: len as u8, buf }))
399		} else {
400			// Joined on the stack, which `arrayvec` leaves uninitialized, so the shared buffer
401			// is the only allocation: a `String` would be a second, copied again into it.
402			let mut buf = arrayvec::ArrayString::<{ Self::MAX_BYTES }>::new();
403			buf.push_str(a);
404			buf.push('/');
405			buf.push_str(b);
406			Ok(Path(Repr::Shared {
407				buf: buf.as_str().into(),
408				start: 0,
409			}))
410		}
411	}
412
413	/// Resolve a [`Relative`] against this path.
414	///
415	/// A non-empty reference replaces the last segment of the base, matching relative URL
416	/// resolution. `..` segments then pop another segment; other segments are appended.
417	/// Excess `..` is a no-op once the base is empty (subsequent named segments still append).
418	/// An empty `rel` returns this path unchanged.
419	///
420	/// [`Relative::new`] strips redundant `.` segments, but preserves a lone `.` so it can
421	/// reference the base's parent.
422	///
423	/// Fails if the result is longer than [`Path::MAX_BYTES`].
424	///
425	/// # Examples
426	/// ```
427	/// use moq_net::{Path, path::Relative};
428	///
429	/// let base = Path::from_static("a/b/c");
430	/// assert_eq!(base.resolve(&Relative::new("./d")?)?.as_str(), "a/b/d");
431	/// assert_eq!(base.resolve(&Relative::new(".")?)?.as_str(), "a/b");
432	/// assert_eq!(base.resolve(&Relative::new("../d")?)?.as_str(), "a/d");
433	/// # Ok::<(), moq_net::path::Error>(())
434	/// ```
435	pub fn resolve(&self, rel: &Relative) -> Result<Path, Error> {
436		if rel.is_empty() {
437			return Ok(self.clone());
438		}
439
440		let mut segments: Vec<&str> = self.parts().collect();
441		segments.pop();
442
443		for seg in rel.0.parts() {
444			if seg == "." {
445				continue;
446			} else if seg == ".." {
447				segments.pop();
448			} else {
449				segments.push(seg);
450			}
451		}
452
453		// Whole segments of valid paths rejoin into a valid path, unless it is too long.
454		Path::new(&segments.join("/"))
455	}
456
457	/// Resolve a [`Relative`], returning `None` if it escapes above the root or
458	/// [`Path::resolve`] would fail.
459	///
460	/// Unlike [`Path::resolve`], this distinguishes a valid reference to the empty root
461	/// path from excess `..` segments. Use it when an untrusted relative reference must
462	/// not be clamped to the root.
463	pub fn try_resolve(&self, rel: &Relative) -> Option<Path> {
464		if rel.is_empty() {
465			return Some(self.clone());
466		}
467
468		let mut segments: Vec<&str> = self.parts().collect();
469		segments.pop();
470
471		for seg in rel.0.parts() {
472			if seg == "." {
473				continue;
474			} else if seg == ".." {
475				segments.pop()?;
476			} else {
477				segments.push(seg);
478			}
479		}
480
481		Path::new(&segments.join("/")).ok()
482	}
483
484	/// Express this path relative to `base`: the inverse of [`Path::resolve`].
485	///
486	/// The result round-trips (`base.resolve(&rel) == self`) and never walks above the
487	/// root, so [`Path::try_resolve`] accepts it too.
488	///
489	/// A relative reference replaces the last segment of the base, matching relative URL
490	/// resolution, so a target nested under the base repeats the base's own last segment.
491	///
492	/// The empty reference names the base itself, so that is what a self-reference returns.
493	///
494	/// Returns `None` for a target no reference can name: a path segment may literally be
495	/// `.` or `..`, which resolution reads as navigation instead of as a name. Only the
496	/// segments past the shared prefix matter, since the rest are never emitted. A
497	/// reference longer than [`Path::MAX_BYTES`] can't be named either.
498	///
499	/// # Examples
500	/// ```
501	/// use moq_net::Path;
502	///
503	/// // The base names a broadcast, so its last segment is replaced, not descended into.
504	/// let base = Path::from_static("a/b");
505	/// assert_eq!(Path::from_static("a/b/c").relative(&base).unwrap().as_str(), "b/c");
506	/// assert_eq!(Path::from_static("a/c").relative(&base).unwrap().as_str(), "c");
507	/// assert_eq!(Path::from_static("c").relative(&base).unwrap().as_str(), "../c");
508	///
509	/// // The lone `.` names the base's parent, which the empty reference cannot.
510	/// assert_eq!(Path::from_static("a").relative(&base).unwrap().as_str(), ".");
511	///
512	/// // The base itself.
513	/// assert_eq!(Path::from_static("a/b").relative(&base).unwrap().as_str(), "");
514	///
515	/// // A segment named `..` is a legal path component but an unnameable target.
516	/// assert!(Path::from_static("a/..").relative(&base).is_none());
517	/// ```
518	pub fn relative(&self, base: &Path) -> Option<Relative> {
519		// Only the empty reference can name a base whose last segment is itself `.` or `..`,
520		// since resolution replaces that segment rather than emitting it.
521		if self == base {
522			return Some(Relative::empty());
523		}
524
525		// Resolution replaces the base's last segment, so walk from its parent.
526		let mut dir: Vec<&str> = base.parts().collect();
527		dir.pop();
528
529		let target: Vec<&str> = self.parts().collect();
530		let common = dir.iter().zip(&target).take_while(|(a, b)| a == b).count();
531
532		let down = &target[common..];
533		if down.iter().any(|part| *part == "." || *part == "..") {
534			// Resolution would walk on these instead of naming them.
535			return None;
536		}
537
538		let mut rel: Vec<&str> = vec![".."; dir.len() - common];
539		rel.extend(down);
540
541		if rel.is_empty() {
542			// An empty reference resolves to the base itself, so name the parent explicitly.
543			return Some(Relative(Path::from_static(".")));
544		}
545
546		Relative::new(&rel.join("/")).ok()
547	}
548}
549
550// `root/path` for logs, without building the joined path.
551#[cfg(feature = "async")]
552pub(crate) struct Rooted<'a>(pub &'a Path, pub &'a Path);
553
554#[cfg(feature = "async")]
555impl Display for Rooted<'_> {
556	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
557		match (self.0.is_empty(), self.1.is_empty()) {
558			(_, true) => write!(f, "{}", self.0),
559			(true, false) => write!(f, "{}", self.1),
560			(false, false) => write!(f, "{}/{}", self.0, self.1),
561		}
562	}
563}
564
565// An entry point's path argument, failing with the entry point's own error type.
566pub(crate) fn convert<E>(path: impl TryInto<Path, Error: Into<E>>) -> Result<Path, E> {
567	path.try_into().map_err(Into::into)
568}
569
570// Comparisons, ordering, and hashing all go through `as_str()` so paths with the same
571// content behave identically whatever their representation (e.g. as map keys).
572impl PartialEq for Path {
573	fn eq(&self, other: &Path) -> bool {
574		self.as_str() == other.as_str()
575	}
576}
577
578impl Eq for Path {}
579
580impl PartialOrd for Path {
581	fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
582		Some(self.cmp(other))
583	}
584}
585
586impl Ord for Path {
587	fn cmp(&self, other: &Self) -> std::cmp::Ordering {
588		self.as_str().cmp(other.as_str())
589	}
590}
591
592impl std::hash::Hash for Path {
593	fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
594		self.as_str().hash(state)
595	}
596}
597
598/// Look up a `Path`-keyed map by `&str` without building a `Path`. The key must be a valid path.
599impl std::borrow::Borrow<str> for Path {
600	fn borrow(&self) -> &str {
601		self.as_str()
602	}
603}
604
605impl fmt::Debug for Path {
606	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
607		f.debug_tuple("Path").field(&self.as_str()).finish()
608	}
609}
610
611impl serde::Serialize for Path {
612	fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
613		serializer.serialize_str(self.as_str())
614	}
615}
616
617impl TryFrom<&str> for Path {
618	type Error = Error;
619
620	fn try_from(s: &str) -> Result<Self, Error> {
621		Self::new(s)
622	}
623}
624
625impl TryFrom<&String> for Path {
626	type Error = Error;
627
628	fn try_from(s: &String) -> Result<Self, Error> {
629		Self::new(s)
630	}
631}
632
633impl From<&Path> for Path {
634	fn from(p: &Path) -> Self {
635		p.clone()
636	}
637}
638
639impl Default for Path {
640	fn default() -> Self {
641		Path::empty()
642	}
643}
644
645impl TryFrom<String> for Path {
646	type Error = Error;
647
648	fn try_from(s: String) -> Result<Self, Error> {
649		// `Arc<str>` can't adopt a `String`'s buffer, so this copies like `new`.
650		Self::new(&s)
651	}
652}
653
654impl AsRef<str> for Path {
655	fn as_ref(&self) -> &str {
656		self.as_str()
657	}
658}
659
660impl Display for Path {
661	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
662		write!(f, "{}", self.as_str())
663	}
664}
665
666impl From<Error> for DecodeError {
667	fn from(err: Error) -> Self {
668		match err {
669			Error::TooLong => DecodeError::BoundsExceeded,
670			Error::EmptySegment | Error::InvalidEscape => DecodeError::InvalidValue,
671		}
672	}
673}
674
675impl From<Error> for crate::Error {
676	fn from(err: Error) -> Self {
677		match err {
678			Error::TooLong => crate::Error::BoundsExceeded(crate::BoundsExceeded),
679			err => crate::Error::Path(err),
680		}
681	}
682}
683
684impl<'a, V> Decode<'a, V> for Path {
685	fn decode(r: &mut Decoder<'a>, _: V) -> Result<Self, DecodeError> {
686		// Borrowed from the wire bytes, so the path's own copy is the only one.
687		let path = Path::new(r.str()?)?;
688		if path.depth() > Path::MAX_PARTS {
689			return Err(DecodeError::BoundsExceeded);
690		}
691		Ok(path)
692	}
693}
694
695impl<V> Encode<V> for Path {
696	fn encode(&self, w: &mut Encoder<'_>, _: V) -> Result<(), EncodeError> {
697		if self.depth() > Path::MAX_PARTS {
698			return Err(EncodeError::BoundsExceeded);
699		}
700		w.string(self.as_str())
701	}
702}
703
704/// A grant's prefixes as a count and each one's text, as AUTH_OK carries them.
705impl<V> Encode<V> for Prefixes {
706	fn encode(&self, w: &mut Encoder<'_>, _: V) -> Result<(), EncodeError> {
707		w.varint(self.len() as u64)?;
708		for prefix in self {
709			w.string(prefix.as_str())?;
710		}
711		Ok(())
712	}
713}
714
715impl<'a, V> Decode<'a, V> for Prefixes {
716	fn decode(r: &mut Decoder<'a>, _: V) -> Result<Self, DecodeError> {
717		let count = r.varint()?;
718		// No preallocation: the count is peer-controlled, and the message size limit
719		// is what bounds how many prefixes actually fit.
720		let mut prefixes = Vec::new();
721		for _ in 0..count {
722			// A wildcard is refused like any other malformed prefix.
723			let prefix = Prefix::try_from(r.string()?).map_err(|_| DecodeError::InvalidValue)?;
724			prefixes.push(prefix);
725		}
726		// Reduce once, in one sort, so a peer's count never turns into quadratic work.
727		Ok(prefixes.into_iter().collect())
728	}
729}
730
731/// A relative broadcast path, used to reference one broadcast from another broadcast's content.
732///
733/// Unlike [`Path`] (which is a complete reference within the broadcast namespace),
734/// `Relative` may contain `.` and `..` segments to walk the namespace and is meaningful
735/// only when resolved against a base [`Path`] via [`Path::resolve`]. The hang catalog uses it
736/// to point a rendition at a track published in a sibling broadcast (e.g. `./source`).
737///
738/// `Relative` has no `Encode`/`Decode` impl, so it never appears in announce/subscribe
739/// frames. It does serialize via serde for off-wire use (e.g. as a field inside a catalog
740/// JSON payload, which itself travels as a track).
741///
742/// It is spelled like a [`Path`], so a leading, trailing, or doubled `/` or a lone `\` is
743/// refused rather than collapsed, and an escaped `/` never splits a segment. Redundant `.` segments are stripped on creation. A reference
744/// made only of `.` segments normalizes to `.` rather than empty because `.` resolves to the
745/// base's parent while empty resolves to the base itself. `..` is preserved for resolve time.
746///
747/// # Examples
748/// ```
749/// use moq_net::{Path, path::Relative};
750///
751/// let rel = Relative::new("./source")?;
752/// assert_eq!(Path::from_static("a/b").resolve(&rel)?.as_str(), "a/source");
753///
754/// // Redundant `.` segments are stripped on creation.
755/// assert_eq!(Relative::new("./a/./b")?.as_str(), "a/b");
756/// assert_eq!(Relative::new(".")?.as_str(), ".");
757///
758/// // An empty segment is refused, not collapsed.
759/// assert!(Relative::new("./a/").is_err());
760/// # Ok::<(), moq_net::path::Error>(())
761/// ```
762#[derive(Debug, PartialEq, Eq, Hash, Clone, Default)]
763pub struct Relative(Path);
764
765impl serde::Serialize for Relative {
766	fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
767		self.0.serialize(serializer)
768	}
769}
770
771impl Relative {
772	/// Create a new `Relative` from a string slice.
773	///
774	/// Fails like [`Path::new`] on a string that is not a valid path, and strips redundant
775	/// `.` segments from one that is. See the type-level doc for the full rules.
776	pub fn new(s: &str) -> Result<Self, Error> {
777		let path = Path::new(s)?;
778		if !path.parts().any(|seg| seg == ".") {
779			return Ok(Self(path));
780		}
781		// Dropping whole segments leaves a valid path no longer than this one.
782		Ok(Self(Path::new(&normalize_relative_segments(&path))?))
783	}
784
785	/// The normalized path as a string slice.
786	pub fn as_str(&self) -> &str {
787		self.0.as_str()
788	}
789
790	/// The empty relative path, which resolves to the base path itself.
791	pub const fn empty() -> Relative {
792		Relative(Path::empty())
793	}
794
795	/// True if the path is empty (resolves to the base path itself).
796	pub fn is_empty(&self) -> bool {
797		self.0.is_empty()
798	}
799
800	/// The length of the normalized path in bytes.
801	pub fn len(&self) -> usize {
802		self.0.len()
803	}
804}
805
806impl TryFrom<&str> for Relative {
807	type Error = Error;
808
809	fn try_from(s: &str) -> Result<Self, Error> {
810		Self::new(s)
811	}
812}
813
814impl TryFrom<&String> for Relative {
815	type Error = Error;
816
817	fn try_from(s: &String) -> Result<Self, Error> {
818		Self::new(s)
819	}
820}
821
822impl TryFrom<String> for Relative {
823	type Error = Error;
824
825	fn try_from(s: String) -> Result<Self, Error> {
826		Self::new(&s)
827	}
828}
829
830// A valid path with at least one `.` segment, without its redundant ones.
831fn normalize_relative_segments(path: &Path) -> String {
832	let segments = path.parts().filter(|seg| *seg != ".").collect::<Vec<_>>().join("/");
833	if segments.is_empty() { ".".to_string() } else { segments }
834}
835
836impl AsRef<str> for Relative {
837	fn as_ref(&self) -> &str {
838		self.as_str()
839	}
840}
841
842impl Display for Relative {
843	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
844		write!(f, "{}", self.as_str())
845	}
846}
847
848impl<'de> serde::Deserialize<'de> for Relative {
849	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
850	where
851		D: serde::Deserializer<'de>,
852	{
853		let s = String::deserialize(deserializer)?;
854		Relative::new(&s).map_err(serde::de::Error::custom)
855	}
856}
857
858#[cfg(test)]
859mod tests {
860	use super::*;
861
862	fn p(s: &str) -> Path {
863		Path::new(s).unwrap()
864	}
865
866	#[test]
867	fn test_refuses_empty_segments() {
868		for s in ["/", "//", "/foo", "foo/", "/foo/", "foo//bar", "foo/bar/", "a///b"] {
869			assert_eq!(Path::new(s), Err(Error::EmptySegment), "accepted {s:?}");
870			assert_eq!(
871				Path::try_from(s.to_string()),
872				Err(Error::EmptySegment),
873				"accepted owned {s:?}"
874			);
875		}
876
877		// The root has no segments, so none of them is empty.
878		assert!(Path::new("").unwrap().is_empty());
879		assert_eq!(Path::try_from(String::new()).unwrap(), Path::empty());
880
881		// Every constructor agrees on everything else.
882		for s in ["foo", "foo/bar", ".hidden/x", "a/../b"] {
883			assert_eq!(p(s).as_str(), s);
884			assert_eq!(p(s), Path::try_from(s.to_string()).unwrap());
885		}
886	}
887
888	#[test]
889	fn test_refuses_invalid_escapes() {
890		for s in [r"\", r"a\", r"\a", r"a\b", r"a\\\b", r"a\\\", r"a\.b/c"] {
891			assert_eq!(Path::new(s), Err(Error::InvalidEscape), "accepted {s:?}");
892			assert_eq!(Relative::new(s), Err(Error::InvalidEscape), "accepted relative {s:?}");
893		}
894
895		// An escape takes exactly the byte after it, so runs of backslashes pair up.
896		for s in [r"\\", r"a\/b", r"\/a", r"a\\/b", r"a\\\/b", r"\\\\"] {
897			assert_eq!(p(s).as_str(), s);
898		}
899	}
900
901	#[test]
902	fn test_an_escaped_separator_is_content() {
903		// An escaped `/` neither ends nor empties a segment, wherever it sits.
904		for s in [r"\/a", r"\/\/a", r"a/\/b"] {
905			assert_eq!(p(s).as_str(), s, "refused {s:?}");
906			assert!(p(s).parts().all(|part| !part.is_empty()), "{s:?}");
907		}
908		// TEMPORARY MIGRATION, delete at the next version cut and move these up: the previous
909		// release would trim or collapse the bare `/` an escaped one leaves at an end or
910		// doubled, re-spelling the path, so they are refused until it is gone.
911		for s in [r"\/", r"a\/", r"a\//b", r"\/\/", r"a/\/", r"\//a"] {
912			assert_eq!(Path::new(s), Err(Error::EmptySegment), "accepted {s:?}");
913		}
914		// A bare one beside it still does.
915		for s in [r"a\///b", r"/\/", r"\//", r"a\\/", r"\\//a"] {
916			assert_eq!(Path::new(s), Err(Error::EmptySegment), "accepted {s:?}");
917		}
918
919		let path = p(r"room/a\/b/.c\/d");
920		assert_eq!(path.parts().collect::<Vec<_>>(), ["room", r"a\/b", r".c\/d"]);
921		assert!(path.has_prefix(&p(r"room/a\/b")));
922		assert!(!path.has_prefix(&p("room/a")));
923		assert_eq!(path.strip_prefix(&p(r"room/a\/b")), Some(p(r".c\/d")));
924		assert!(path.is_hidden());
925		// No field starts with `.`, so nothing hides.
926		assert!(!p(r"a\/.b").is_hidden());
927		assert_eq!(
928			path.parts().map(|part| unescape(part).into_owned()).collect::<Vec<_>>(),
929			["room", "a/b", ".c/d"]
930		);
931	}
932
933	#[test]
934	#[should_panic(expected = "empty segment")]
935	fn test_from_static_refuses_empty_segments() {
936		Path::from_static("a//b");
937	}
938
939	#[test]
940	fn test_decode_refuses_empty_segments() {
941		use crate::lite::Version;
942
943		for s in ["/foo", "foo/", "foo//bar"] {
944			let mut buf = Vec::new();
945			Encoder::new(&mut buf, Version::Lite04.into()).string(s).unwrap();
946			assert!(matches!(
947				crate::coding::decode_buf(&mut bytes::Bytes::from(buf), Version::Lite04, |r, v| Path::decode(r, v)),
948				Err(DecodeError::InvalidValue)
949			));
950		}
951	}
952
953	#[test]
954	fn test_has_prefix() {
955		let path = p("foo/bar/baz");
956
957		assert!(path.has_prefix(&Path::empty()));
958		assert!(path.has_prefix(&p("foo")));
959		assert!(path.has_prefix(&p("foo/bar")));
960		assert!(path.has_prefix(&p("foo/bar/baz")));
961
962		// Only whole segments match.
963		assert!(!path.has_prefix(&p("f")));
964		assert!(!path.has_prefix(&p("fo")));
965		assert!(!path.has_prefix(&p("foo/b")));
966		assert!(!path.has_prefix(&p("foo/ba")));
967		assert!(!path.has_prefix(&p("foo/bar/ba")));
968		assert!(!p("foobar").has_prefix(&p("foo")));
969		assert!(p("foobar").has_prefix(&p("foobar")));
970
971		// The root prefixes everything, and is prefixed only by itself.
972		assert!(Path::empty().has_prefix(&Path::empty()));
973		assert!(!Path::empty().has_prefix(&p("foo")));
974	}
975
976	#[test]
977	fn test_strip_prefix() {
978		let path = p("foo/bar/baz");
979
980		assert_eq!(path.strip_prefix(&Path::empty()).unwrap().as_str(), "foo/bar/baz");
981		assert_eq!(path.strip_prefix(&p("foo")).unwrap().as_str(), "bar/baz");
982		assert_eq!(path.strip_prefix(&p("foo/bar")).unwrap().as_str(), "baz");
983		assert_eq!(path.strip_prefix(&p("foo/bar/baz")).unwrap().as_str(), "");
984
985		assert!(path.strip_prefix(&p("fo")).is_none());
986		assert!(path.strip_prefix(&p("bar")).is_none());
987		assert!(path.strip_prefix(&p("foo/ba")).is_none());
988		assert!(p("foobar").strip_prefix(&p("foo")).is_none());
989
990		assert_eq!(Path::empty().strip_prefix(&Path::empty()).unwrap().as_str(), "");
991		assert!(Path::empty().strip_prefix(&p("foo")).is_none());
992	}
993
994	#[test]
995	fn test_head() {
996		let path = p("foo/bar/baz");
997		assert_eq!(path.head(1), Some(p("foo")));
998		assert_eq!(path.head(3), Some(path.clone()));
999		assert_eq!(path.head(4), None);
1000		assert_eq!(Path::empty().head(0), Some(Path::empty()));
1001		assert_eq!(Path::empty().head(1), None);
1002
1003		// A long path's head is a valid path of its own.
1004		let long = p(&format!("{}/tail", "a".repeat(INLINE + 1)));
1005		assert_eq!(long.head(1).unwrap().as_str(), "a".repeat(INLINE + 1));
1006
1007		// An escaped `/` is inside its segment, and an escaped `\` before a separator is whole.
1008		let escaped = p(r"a\/b/c\\/d");
1009		assert_eq!(escaped.head(1), Some(p(r"a\/b")));
1010		assert_eq!(escaped.head(2), Some(p(r"a\/b/c\\")));
1011		assert_eq!(escaped.head(3), Some(escaped.clone()));
1012		assert_eq!(escaped.head(4), None);
1013	}
1014
1015	#[test]
1016	fn test_join() {
1017		assert_eq!(p("foo").join(&p("bar")).unwrap().as_str(), "foo/bar");
1018		assert_eq!(p("foo/bar").join(&p("baz/qux")).unwrap().as_str(), "foo/bar/baz/qux");
1019
1020		// The root is the identity on either side.
1021		assert_eq!(p("foo").join(&Path::empty()).unwrap().as_str(), "foo");
1022		assert_eq!(Path::empty().join(&p("bar")).unwrap().as_str(), "bar");
1023		assert_eq!(Path::empty().join(&Path::empty()).unwrap().as_str(), "");
1024	}
1025
1026	// A long path shares one allocation through the clone and strip_prefix flow used by
1027	// announce fan-out. A short one is stored inline instead, so its copies share nothing.
1028	#[test]
1029	fn test_long_paths_share_allocation() {
1030		let path = Path::new("customer/room-0123456789/broadcast").unwrap();
1031
1032		// Cloning shares the buffer.
1033		let cloned = path.clone();
1034		assert_eq!(path.as_str().as_ptr(), cloned.as_str().as_ptr());
1035
1036		// Stripping a prefix leaving a long rest is offset arithmetic, not a copy.
1037		let stripped = path.strip_prefix(&Path::from_static("customer")).unwrap();
1038		assert_eq!(stripped.as_str(), "room-0123456789/broadcast");
1039		assert_eq!(stripped.as_str().as_ptr(), path.as_str()["customer/".len()..].as_ptr());
1040
1041		// A short rest moves inline rather than keeping the long buffer alive.
1042		let short = path
1043			.strip_prefix(&Path::from_static("customer/room-0123456789"))
1044			.unwrap();
1045		assert_eq!(short.as_str(), "broadcast");
1046		assert!(matches!(short.0, Repr::Inline { .. }));
1047
1048		// join produces a path whose clones share.
1049		let joined = path.join(&Path::from_static("alice")).unwrap();
1050		let joined2 = joined.clone();
1051		assert_eq!(joined.as_str(), "customer/room-0123456789/broadcast/alice");
1052		assert_eq!(joined.as_str().as_ptr(), joined2.as_str().as_ptr());
1053	}
1054
1055	#[test]
1056	fn test_inline_boundary() {
1057		let fits = "a".repeat(INLINE);
1058		let spills = "a".repeat(INLINE + 1);
1059		assert!(matches!(Path::new(&fits).unwrap().0, Repr::Inline { .. }));
1060		assert!(matches!(Path::new(&spills).unwrap().0, Repr::Shared { .. }));
1061
1062		// A join exactly at the limit stays inline; one byte more spills.
1063		let half = Path::new(&"b".repeat(INLINE / 2 - 1)).unwrap();
1064		let joined = half.join(&Path::new(&"c".repeat(INLINE / 2)).unwrap()).unwrap();
1065		assert_eq!(joined.len(), INLINE);
1066		assert!(matches!(joined.0, Repr::Inline { .. }));
1067		assert_eq!(
1068			joined.as_str(),
1069			format!("{}/{}", "b".repeat(INLINE / 2 - 1), "c".repeat(INLINE / 2))
1070		);
1071		assert!(matches!(
1072			joined.join(&Path::from_static("d")).unwrap().0,
1073			Repr::Shared { .. }
1074		));
1075
1076		// Multi-byte characters survive the inline copy.
1077		let wide = Path::new("caf\u{e9}/\u{1f3a5}").unwrap();
1078		assert!(matches!(wide.0, Repr::Inline { .. }));
1079		assert_eq!(wide.as_str(), "caf\u{e9}/\u{1f3a5}");
1080		assert_eq!(
1081			wide.strip_prefix(&Path::from_static("caf\u{e9}")).unwrap().as_str(),
1082			"\u{1f3a5}"
1083		);
1084	}
1085
1086	#[test]
1087	fn test_max_bytes() {
1088		let longest = "a".repeat(Path::MAX_BYTES);
1089		let longer = format!("{longest}b");
1090
1091		// Every constructor accepts the limit and refuses one byte more.
1092		assert_eq!(Path::new(&longest).unwrap().len(), Path::MAX_BYTES);
1093		assert_eq!(Path::new(&longer), Err(Error::TooLong));
1094		assert_eq!(Path::try_from(longer.clone()), Err(Error::TooLong));
1095		assert_eq!(Relative::new(&longer), Err(Error::TooLong));
1096
1097		// So do joins and resolution, which can outgrow both sides.
1098		let half = Path::new(&"a".repeat(Path::MAX_BYTES / 2)).unwrap();
1099		let rest = Path::new(&"b".repeat(Path::MAX_BYTES / 2 - 1)).unwrap();
1100		assert_eq!(half.join(&rest).unwrap().len(), Path::MAX_BYTES);
1101		assert_eq!(half.join(&Path::new(&format!("{rest}b")).unwrap()), Err(Error::TooLong));
1102		let rel = Relative::new(&format!("x/{rest}b")).unwrap();
1103		assert_eq!(
1104			Path::new(&format!("{half}/y")).unwrap().resolve(&rel),
1105			Err(Error::TooLong)
1106		);
1107		assert_eq!(Path::new(&format!("{half}/y")).unwrap().try_resolve(&rel), None);
1108
1109		// A suffix at the deepest offset still shares the buffer.
1110		let tail = "c".repeat(INLINE + 1);
1111		let head = "a".repeat(Path::MAX_BYTES - tail.len() - 1);
1112		let path = Path::new(&format!("{head}/{tail}")).unwrap();
1113		let at = path.strip_prefix(&Path::new(&head).unwrap()).unwrap();
1114		assert_eq!(at.as_str(), tail);
1115		assert_eq!(at.as_str().as_ptr(), path.as_str()[head.len() + 1..].as_ptr());
1116	}
1117
1118	#[test]
1119	#[should_panic(expected = "longer than")]
1120	fn test_from_static_too_long() {
1121		// A static rather than a leaked string, which Miri would report.
1122		static LITERAL: [u8; Path::MAX_BYTES + 1] = [b'a'; Path::MAX_BYTES + 1];
1123		Path::from_static(std::str::from_utf8(&LITERAL).unwrap());
1124	}
1125
1126	#[test]
1127	fn test_from_static_borrows() {
1128		const LITERAL: &str = "static/path/that/is/longer/than/inline";
1129		let path = Path::from_static(LITERAL);
1130		assert_eq!(path.as_str(), LITERAL);
1131		assert_eq!(path.as_str().as_ptr(), LITERAL.as_ptr());
1132
1133		// A suffix or head of a static path borrows the literal too.
1134		let rest = path.strip_prefix(&Path::from_static("static")).unwrap();
1135		assert_eq!(rest.as_str().as_ptr(), LITERAL["static/".len()..].as_ptr());
1136		assert_eq!(path.head(2).unwrap().as_str().as_ptr(), LITERAL.as_ptr());
1137	}
1138
1139	#[test]
1140	fn test_parts() {
1141		assert_eq!(Path::empty().parts().count(), 0);
1142		assert_eq!(Path::from_static("foo").parts().collect::<Vec<_>>(), ["foo"]);
1143		assert_eq!(Path::from_static("foo/bar").parts().collect::<Vec<_>>(), ["foo", "bar"]);
1144		assert_eq!(
1145			Path::from_static(r"foo\/bar/baz").parts().rev().collect::<Vec<_>>(),
1146			["baz", r"foo\/bar"]
1147		);
1148	}
1149
1150	#[test]
1151	fn test_wire_max_parts() {
1152		use crate::lite::Version;
1153
1154		let ok = (0..Path::MAX_PARTS)
1155			.map(|i| i.to_string())
1156			.collect::<Vec<_>>()
1157			.join("/");
1158		let too_deep = format!("{ok}/extra");
1159
1160		// Encode enforces the limit.
1161		let mut buf = Vec::new();
1162		Path::new(&ok)
1163			.unwrap()
1164			.encode(&mut Encoder::new(&mut buf, Version::Lite04.into()), Version::Lite04)
1165			.unwrap();
1166		assert!(matches!(
1167			Path::new(&too_deep).unwrap().encode_bytes(Version::Lite04),
1168			Err(EncodeError::BoundsExceeded)
1169		));
1170
1171		// Decode round-trips at the limit.
1172		let decoded =
1173			crate::coding::decode_buf(&mut bytes::Bytes::from(buf), Version::Lite04, |r, v| Path::decode(r, v))
1174				.unwrap();
1175		assert_eq!(decoded.as_str(), ok);
1176
1177		// Decode refuses a raw string longer than the limit.
1178		let mut buf = Vec::new();
1179		Encoder::new(&mut buf, Version::Lite04.into())
1180			.string(too_deep.as_str())
1181			.unwrap();
1182		assert!(matches!(
1183			crate::coding::decode_buf(&mut bytes::Bytes::from(buf), Version::Lite04, |r, v| Path::decode(r, v)),
1184			Err(DecodeError::BoundsExceeded)
1185		));
1186
1187		// TEMPORARY MIGRATION, delete at the next version cut and expect a round trip: the
1188		// previous release counts every `/` and ends the whole announce stream past 32, so an
1189		// escaped `/` still counts against the limit, though it separates nothing.
1190		let escaped = (0..Path::MAX_PARTS)
1191			.map(|i| format!(r"{i}\/{i}"))
1192			.collect::<Vec<_>>()
1193			.join("/");
1194		let escaped = Path::new(&escaped).unwrap();
1195		assert_eq!(escaped.parts().count(), Path::MAX_PARTS);
1196		assert!(matches!(
1197			escaped.encode_bytes(Version::Lite07),
1198			Err(EncodeError::BoundsExceeded)
1199		));
1200	}
1201
1202	#[test]
1203	fn test_wire_max_len() {
1204		use crate::lite::Version;
1205
1206		let longest = "a".repeat(Path::MAX_BYTES);
1207		let longer = format!("{longest}b");
1208
1209		// Decode round-trips at the limit.
1210		let mut buf = Path::new(&longest).unwrap().encode_bytes(Version::Lite04).unwrap();
1211		let decoded = crate::coding::decode_buf(&mut buf, Version::Lite04, |r, v| Path::decode(r, v)).unwrap();
1212		assert_eq!(decoded.as_str(), longest);
1213
1214		// A message carrying the longest path still fits the lite message limit.
1215		let tracks = crate::lite::Tracks {
1216			broadcast: Path::new(&longest).unwrap(),
1217			identity: None,
1218			node: None,
1219		};
1220		let buf = tracks.encode_bytes(Version::Lite07).unwrap();
1221		let (decoded, _) = crate::lite::Tracks::decode_slice(&buf, Version::Lite07).unwrap();
1222		assert_eq!(decoded.broadcast.as_str(), longest);
1223
1224		// Decode refuses a raw string longer than the limit.
1225		let mut buf = Vec::new();
1226		Encoder::new(&mut buf, Version::Lite04.into()).string(&longer).unwrap();
1227		assert!(matches!(
1228			crate::coding::decode_buf(&mut bytes::Bytes::from(buf), Version::Lite04, |r, v| Path::decode(r, v)),
1229			Err(DecodeError::BoundsExceeded)
1230		));
1231	}
1232
1233	#[test]
1234	fn test_owned_empty_paths() {
1235		// Empty paths never allocate and stay well-behaved.
1236		let empty = Path::from_static("");
1237		assert!(empty.is_empty());
1238		assert_eq!(empty, Path::empty());
1239
1240		let path = Path::from_static("foo");
1241		let rest = path.strip_prefix(&Path::from_static("foo")).unwrap();
1242		assert!(rest.is_empty());
1243	}
1244
1245	#[test]
1246	fn test_path_relative_refuses_empty_segments() {
1247		assert_eq!(Relative::new("foo").unwrap().as_str(), "foo");
1248		assert_eq!(Relative::new("../foo").unwrap().as_str(), "../foo");
1249		assert_eq!(Relative::new("../../a/b").unwrap().as_str(), "../../a/b");
1250		assert!(Relative::new("").unwrap().is_empty());
1251
1252		for s in ["/", "/foo", "foo/", "./", "foo//bar", "./foo/", "../"] {
1253			assert_eq!(Relative::new(s), Err(Error::EmptySegment), "accepted {s:?}");
1254		}
1255	}
1256
1257	#[test]
1258	fn test_path_relative_normalizes_dot_segments() {
1259		assert_eq!(Relative::new(".").unwrap().as_str(), ".");
1260		assert_eq!(Relative::new("./.").unwrap().as_str(), ".");
1261		assert_eq!(Relative::new("./foo").unwrap().as_str(), "foo");
1262		// A `.` after an escaped `/` is inside its segment, not one of its own.
1263		assert_eq!(Relative::new(r"a\/.").unwrap().as_str(), r"a\/.");
1264		assert_eq!(Relative::new(r"./a\/.").unwrap().as_str(), r"a\/.");
1265		assert_eq!(Relative::new(r"a\\/.").unwrap().as_str(), r"a\\");
1266		assert_eq!(Relative::new("foo/./bar").unwrap().as_str(), "foo/bar");
1267		assert_eq!(Relative::new("./../foo").unwrap().as_str(), "../foo");
1268		// TryFrom<String> takes the same normalization.
1269		assert_eq!(Relative::try_from("./foo".to_string()).unwrap().as_str(), "foo");
1270		assert_eq!(Relative::try_from(".".to_string()).unwrap().as_str(), ".");
1271	}
1272
1273	#[test]
1274	fn test_resolve_replaces_base_name() {
1275		let base = Path::from_static("a/b");
1276		assert_eq!(base.resolve(&Relative::new("c").unwrap()).unwrap().as_str(), "a/c");
1277		assert_eq!(base.resolve(&Relative::new("c/d").unwrap()).unwrap().as_str(), "a/c/d");
1278		assert_eq!(
1279			Path::from_static("foo.hang/catalog.pro")
1280				.resolve(&Relative::new("./transcode.pro").unwrap())
1281				.unwrap()
1282				.as_str(),
1283			"foo.hang/transcode.pro"
1284		);
1285	}
1286
1287	#[test]
1288	fn test_resolve_empty_rel_returns_base() {
1289		let base = Path::from_static("a/b");
1290		assert_eq!(base.resolve(&Relative::new("").unwrap()).unwrap().as_str(), "a/b");
1291	}
1292
1293	#[test]
1294	fn test_resolve_single_dotdot() {
1295		let base = Path::from_static("a/b/c");
1296		assert_eq!(base.resolve(&Relative::new("../d").unwrap()).unwrap().as_str(), "a/d");
1297		assert_eq!(base.resolve(&Relative::new("..").unwrap()).unwrap().as_str(), "a");
1298	}
1299
1300	#[test]
1301	fn test_resolve_multiple_dotdot() {
1302		let base = Path::from_static("a/b/c");
1303		assert_eq!(base.resolve(&Relative::new("../../x").unwrap()).unwrap().as_str(), "x");
1304		assert_eq!(
1305			base.resolve(&Relative::new("../../../x").unwrap()).unwrap().as_str(),
1306			"x"
1307		);
1308	}
1309
1310	#[test]
1311	fn test_resolve_dotdot_clamps_at_root() {
1312		let base = Path::from_static("a");
1313		// Excess `..` clamps at the root instead of escaping it.
1314		assert_eq!(
1315			base.resolve(&Relative::new("../../../foo").unwrap()).unwrap().as_str(),
1316			"foo"
1317		);
1318		assert_eq!(base.resolve(&Relative::new("..").unwrap()).unwrap().as_str(), "");
1319	}
1320
1321	#[test]
1322	fn test_resolve_empty_base() {
1323		let base = Path::empty();
1324		assert_eq!(base.resolve(&Relative::new("foo").unwrap()).unwrap().as_str(), "foo");
1325		assert_eq!(base.resolve(&Relative::new("..").unwrap()).unwrap().as_str(), "");
1326	}
1327
1328	#[test]
1329	fn test_resolve_dot_names_parent() {
1330		let base = Path::from_static("a/b");
1331		assert_eq!(base.resolve(&Relative::new(".").unwrap()).unwrap().as_str(), "a");
1332		assert_eq!(base.resolve(&Relative::new("./c").unwrap()).unwrap().as_str(), "a/c");
1333		assert_eq!(base.resolve(&Relative::new("./../c").unwrap()).unwrap().as_str(), "c");
1334	}
1335
1336	#[test]
1337	fn test_resolve_self_reference_via_sibling_name() {
1338		// Naming the base within its parent yields the base unchanged, which lets the
1339		// caller compare resolved == base to detect a self-reference.
1340		let base = Path::from_static("a/b");
1341		assert_eq!(base.resolve(&Relative::new("./b").unwrap()).unwrap().as_str(), "a/b");
1342	}
1343
1344	#[test]
1345	fn test_resolve_walks_whole_escaped_segments() {
1346		// `a\/b` is one segment, so `..` pops all of it.
1347		let base = p(r"a\/b/c/d");
1348		let up = Relative::new("..").unwrap();
1349		assert_eq!(base.resolve(&up), Ok(p(r"a\/b")));
1350		assert_eq!(base.try_resolve(&Relative::new("../..").unwrap()), Some(Path::empty()));
1351		assert_eq!(base.try_resolve(&Relative::new("../../..").unwrap()), None);
1352		assert_eq!(base.resolve(&Relative::new(r"x\/y").unwrap()), Ok(p(r"a\/b/c/x\/y")));
1353
1354		let target = p(r"a\/b/e\/f");
1355		let rel = target.relative(&base).unwrap();
1356		assert_eq!(rel.as_str(), r"../e\/f");
1357		assert_eq!(base.resolve(&rel), Ok(target));
1358	}
1359
1360	#[test]
1361	fn test_try_resolve_distinguishes_root_from_escape() {
1362		let base = Path::from_static("top");
1363		assert_eq!(base.try_resolve(&Relative::new(".").unwrap()).unwrap().as_str(), "");
1364		assert!(base.try_resolve(&Relative::new("..").unwrap()).is_none());
1365
1366		let nested = Path::from_static("a/b");
1367		assert_eq!(nested.try_resolve(&Relative::new("..").unwrap()).unwrap().as_str(), "");
1368		assert!(nested.try_resolve(&Relative::new("../..").unwrap()).is_none());
1369	}
1370
1371	#[test]
1372	fn test_relative() {
1373		let rel = |target: &str, base: &str| Path::new(target).unwrap().relative(&Path::new(base).unwrap()).unwrap();
1374
1375		// Nested under the base: the base's own last segment is replaced, so it repeats.
1376		assert_eq!(rel("foo/bar/baz", "foo/bar").as_str(), "bar/baz");
1377		// Sibling.
1378		assert_eq!(rel("foo/baz", "foo/bar").as_str(), "baz");
1379		// Different subtree.
1380		assert_eq!(rel("foo/baz/bar", "foo/bar/baz").as_str(), "../baz/bar");
1381		// The base's parent, which only `.` can name.
1382		assert_eq!(rel("a/b", "a/b/transcode.hang").as_str(), ".");
1383		assert_eq!(rel("a/b", "a/b/one/two/transcode.hang").as_str(), "../..");
1384		// Roots.
1385		assert_eq!(rel("foo/bar", "").as_str(), "foo/bar");
1386		assert_eq!(rel("", "foo").as_str(), ".");
1387		// The base itself, which only the empty reference names.
1388		assert_eq!(rel("a/b", "a/b").as_str(), "");
1389		assert_eq!(rel("", "").as_str(), "");
1390	}
1391
1392	#[test]
1393	fn test_relative_rejects_unnameable_targets() {
1394		// A segment literally named `.` or `..` is a legal path component, but resolution
1395		// would walk on it instead of naming it.
1396		assert!(Path::from_static("a/../b").relative(&Path::from_static("")).is_none());
1397		assert!(Path::from_static("x/./y").relative(&Path::from_static("x/z")).is_none());
1398		assert!(Path::from_static("a/..").relative(&Path::from_static("a/b")).is_none());
1399
1400		// A base is always nameable by itself, however its last segment is spelled.
1401		assert_eq!(
1402			Path::from_static("a/..")
1403				.relative(&Path::from_static("a/.."))
1404				.unwrap()
1405				.as_str(),
1406			""
1407		);
1408
1409		// Dot segments inside the shared prefix are never emitted, so they are fine.
1410		let rel = Path::from_static("a/../b/x")
1411			.relative(&Path::from_static("a/../b/c"))
1412			.unwrap();
1413		assert_eq!(rel.as_str(), "x");
1414		assert_eq!(
1415			Path::from_static("a/../b/c").resolve(&rel).unwrap().as_str(),
1416			"a/../b/x"
1417		);
1418	}
1419
1420	#[test]
1421	fn test_relative_round_trips() {
1422		let paths = [
1423			"", "a", "b", "a/b", "a/c", "a/b/c", "a/b/c/d", "x/y/z", "a/../b", "a/./b", "a/..", "a/.",
1424		];
1425
1426		for base in paths {
1427			for target in paths {
1428				let base = Path::new(base).unwrap();
1429				let target = Path::new(target).unwrap();
1430				let Some(rel) = target.relative(&base) else {
1431					// Only an unnameable target may be refused, and never the base itself.
1432					assert!(
1433						target != base && target.parts().any(|part| part == "." || part == ".."),
1434						"{base} -> {target} refused a nameable target"
1435					);
1436					continue;
1437				};
1438
1439				assert_eq!(base.resolve(&rel), Ok(target.clone()), "{base} -> {target} via {rel}");
1440				// The reference is derived from a real target, so it never escapes the root.
1441				assert!(
1442					base.try_resolve(&rel).is_some(),
1443					"{base} -> {target} via {rel} escaped the root"
1444				);
1445			}
1446		}
1447	}
1448}