moq_lite/
path.rs

1use std::borrow::Cow;
2use std::fmt::{self, Display};
3
4use crate::coding::{Decode, DecodeError, Encode};
5
6pub type PathOwned = Path<'static>;
7
8/// A trait for types that can be converted to a `Path`.
9///
10/// When providing a String/str, any leading/trailing slashes are trimmed and multiple consecutive slashes are collapsed.
11/// When already a Path, normalization is skipped as a reference is returned.
12pub trait AsPath {
13	fn as_path(&self) -> Path<'_>;
14}
15
16impl<'a> AsPath for &'a str {
17	fn as_path(&self) -> Path<'a> {
18		Path::new(self)
19	}
20}
21
22impl<'a> AsPath for &'a Path<'a> {
23	fn as_path(&self) -> Path<'a> {
24		// We don't normalize again nor do we make a copy.
25		Path(Cow::Borrowed(self.as_str()))
26	}
27}
28
29impl<'a> AsPath for Path<'a> {
30	fn as_path(&self) -> Path<'_> {
31		Path(Cow::Borrowed(self.0.as_ref()))
32	}
33}
34
35impl AsPath for String {
36	fn as_path(&self) -> Path<'_> {
37		Path(Cow::Borrowed(self))
38	}
39}
40
41impl<'a> AsPath for &'a String {
42	fn as_path(&self) -> Path<'a> {
43		Path(Cow::Borrowed(self))
44	}
45}
46
47/// A broadcast path that provides safe prefix matching operations.
48///
49/// This type wraps a String but provides path-aware operations that respect
50/// delimiter boundaries, preventing issues like "foo" matching "foobar".
51///
52/// Paths are automatically trimmed of leading and trailing slashes on creation,
53/// making all slashes implicit at boundaries.
54/// All paths are RELATIVE; you cannot join with a leading slash to make an absolute path.
55///
56/// # Examples
57/// ```
58/// use moq_lite::{Path};
59///
60/// // Creation automatically trims slashes
61/// let path1 = Path::new("/foo/bar/");
62/// let path2 = Path::new("foo/bar");
63/// assert_eq!(path1, path2);
64///
65/// // Methods accept both &str and Path
66/// let base = Path::new("api/v1");
67/// assert!(base.has_prefix("api"));
68/// assert!(base.has_prefix(&Path::new("api/v1")));
69///
70/// let joined = base.join("users");
71/// assert_eq!(joined.as_str(), "api/v1/users");
72/// ```
73#[derive(Debug, PartialEq, Eq, Hash, Clone)]
74#[cfg_attr(feature = "serde", derive(serde::Serialize))]
75pub struct Path<'a>(Cow<'a, str>);
76
77impl<'a> Path<'a> {
78	/// Create a new Path from a string slice.
79	///
80	/// Leading and trailing slashes are automatically trimmed.
81	/// Multiple consecutive internal slashes are collapsed to single slashes.
82	pub fn new(s: &'a str) -> Self {
83		let trimmed = s.trim_start_matches('/').trim_end_matches('/');
84
85		// Check if we need to normalize (has multiple consecutive slashes)
86		if trimmed.contains("//") {
87			// Only allocate if we actually need to normalize
88			let normalized = trimmed
89				.split('/')
90				.filter(|s| !s.is_empty())
91				.collect::<Vec<_>>()
92				.join("/");
93			Self(Cow::Owned(normalized))
94		} else {
95			// No normalization needed - use borrowed string
96			Self(Cow::Borrowed(trimmed))
97		}
98	}
99
100	/// Check if this path has the given prefix, respecting path boundaries.
101	///
102	/// Unlike String::starts_with, this ensures that "foo" does not match "foobar".
103	/// The prefix must either:
104	/// - Be exactly equal to this path
105	/// - Be followed by a '/' delimiter in the original path
106	/// - Be empty (matches everything)
107	///
108	/// # Examples
109	/// ```
110	/// use moq_lite::Path;
111	///
112	/// let path = Path::new("foo/bar");
113	/// assert!(path.has_prefix("foo"));
114	/// assert!(path.has_prefix(&Path::new("foo")));
115	/// assert!(path.has_prefix("foo/"));
116	/// assert!(!path.has_prefix("fo"));
117	///
118	/// let path = Path::new("foobar");
119	/// assert!(!path.has_prefix("foo"));
120	/// ```
121	pub fn has_prefix(&self, prefix: impl AsPath) -> bool {
122		let prefix = prefix.as_path();
123
124		if prefix.is_empty() {
125			return true;
126		}
127
128		if !self.0.starts_with(prefix.as_str()) {
129			return false;
130		}
131
132		// Check if the prefix is the exact match
133		if self.0.len() == prefix.len() {
134			return true;
135		}
136
137		// Otherwise, ensure the character after the prefix is a delimiter
138		self.0.chars().nth(prefix.len()) == Some('/')
139	}
140
141	pub fn strip_prefix(&'a self, prefix: impl AsPath) -> Option<Path<'a>> {
142		let prefix = prefix.as_path();
143
144		if prefix.is_empty() {
145			return Some(self.borrow());
146		}
147
148		if !self.0.starts_with(prefix.as_str()) {
149			return None;
150		}
151
152		// Check if the prefix is the exact match
153		if self.0.len() == prefix.len() {
154			return Some(Path(Cow::Borrowed("")));
155		}
156
157		// Otherwise, ensure the character after the prefix is a delimiter
158		if self.0.chars().nth(prefix.len()) != Some('/') {
159			return None;
160		}
161
162		Some(Path(Cow::Borrowed(&self.0[prefix.len() + 1..])))
163	}
164
165	/// Strip the directory component of the path, if any, and return the rest of the path.
166	pub fn next_part(&'a self) -> Option<(&'a str, Path<'a>)> {
167		if self.0.is_empty() {
168			return None;
169		}
170
171		if let Some(i) = self.0.find('/') {
172			let dir = &self.0[..i];
173			let rest = Path(Cow::Borrowed(&self.0[i + 1..]));
174			Some((dir, rest))
175		} else {
176			Some((&self.0, Path(Cow::Borrowed(""))))
177		}
178	}
179
180	pub fn as_str(&self) -> &str {
181		&self.0
182	}
183
184	pub fn is_empty(&self) -> bool {
185		self.0.is_empty()
186	}
187
188	pub fn len(&self) -> usize {
189		self.0.len()
190	}
191
192	pub fn to_owned(&self) -> PathOwned {
193		Path(Cow::Owned(self.0.to_string()))
194	}
195
196	pub fn into_owned(self) -> PathOwned {
197		Path(Cow::Owned(self.0.to_string()))
198	}
199
200	pub fn borrow(&'a self) -> Path<'a> {
201		Path(Cow::Borrowed(&self.0))
202	}
203
204	/// Join this path with another path component.
205	///
206	/// # Examples
207	/// ```
208	/// use moq_lite::Path;
209	///
210	/// let base = Path::new("foo");
211	/// let joined = base.join("bar");
212	/// assert_eq!(joined.as_str(), "foo/bar");
213	///
214	/// let joined = base.join(&Path::new("bar"));
215	/// assert_eq!(joined.as_str(), "foo/bar");
216	/// ```
217	pub fn join(&self, other: impl AsPath) -> PathOwned {
218		let other = other.as_path();
219
220		if self.0.is_empty() {
221			Path(Cow::Owned(other.0.to_string()))
222		} else if other.is_empty() {
223			// Technically, we could avoid allocating here, but it's nicer to return a PathOwned.
224			self.to_owned()
225		} else {
226			// Since paths are trimmed, we always need to add a slash
227			Path(Cow::Owned(format!("{}/{}", self.0, other.as_str())))
228		}
229	}
230}
231
232impl<'a> From<&'a str> for Path<'a> {
233	fn from(s: &'a str) -> Self {
234		Self::new(s)
235	}
236}
237
238impl<'a> From<&'a String> for Path<'a> {
239	fn from(s: &'a String) -> Self {
240		// TODO avoid making a copy here
241		Self::new(s)
242	}
243}
244
245impl<'a> Default for Path<'a> {
246	fn default() -> Self {
247		Self(Cow::Borrowed(""))
248	}
249}
250
251impl<'a> From<String> for Path<'a> {
252	fn from(s: String) -> Self {
253		// It's annoying that this logic is duplicated, but I couldn't figure out how to reuse Path::new.
254		let trimmed = s.trim_start_matches('/').trim_end_matches('/');
255
256		// Check if we need to normalize (has multiple consecutive slashes)
257		if trimmed.contains("//") {
258			// Only allocate if we actually need to normalize
259			let normalized = trimmed
260				.split('/')
261				.filter(|s| !s.is_empty())
262				.collect::<Vec<_>>()
263				.join("/");
264			Self(Cow::Owned(normalized))
265		} else if trimmed == s {
266			// String is already trimmed and normalized, use it directly
267			Self(Cow::Owned(s))
268		} else {
269			// Need to trim but don't need to normalize internal slashes
270			Self(Cow::Owned(trimmed.to_string()))
271		}
272	}
273}
274
275impl<'a> AsRef<str> for Path<'a> {
276	fn as_ref(&self) -> &str {
277		&self.0
278	}
279}
280
281impl<'a> Display for Path<'a> {
282	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
283		write!(f, "{}", self.0)
284	}
285}
286
287impl<'a> Decode for Path<'a> {
288	fn decode<R: bytes::Buf>(r: &mut R) -> Result<Self, DecodeError> {
289		Ok(String::decode(r)?.into())
290	}
291}
292
293impl<'a> Encode for Path<'a> {
294	fn encode<W: bytes::BufMut>(&self, w: &mut W) {
295		self.as_str().encode(w)
296	}
297}
298
299// A custom deserializer is needed in order to sanitize
300#[cfg(feature = "serde")]
301impl<'de: 'a, 'a> serde::Deserialize<'de> for Path<'a> {
302	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
303	where
304		D: serde::Deserializer<'de>,
305	{
306		let s = <&'a str as serde::Deserialize<'de>>::deserialize(deserializer)?;
307		Ok(Path::new(s))
308	}
309}
310
311#[cfg(test)]
312mod tests {
313	use super::*;
314
315	#[test]
316	fn test_has_prefix() {
317		let path = Path::new("foo/bar/baz");
318
319		// Valid prefixes - test with both &str and &Path
320		assert!(path.has_prefix(""));
321		assert!(path.has_prefix("foo"));
322		assert!(path.has_prefix(Path::new("foo")));
323		assert!(path.has_prefix("foo/"));
324		assert!(path.has_prefix("foo/bar"));
325		assert!(path.has_prefix(Path::new("foo/bar/")));
326		assert!(path.has_prefix("foo/bar/baz"));
327
328		// Invalid prefixes - should not match partial components
329		assert!(!path.has_prefix("f"));
330		assert!(!path.has_prefix(Path::new("fo")));
331		assert!(!path.has_prefix("foo/b"));
332		assert!(!path.has_prefix("foo/ba"));
333		assert!(!path.has_prefix(Path::new("foo/bar/ba")));
334
335		// Edge case: "foobar" should not match "foo"
336		let path = Path::new("foobar");
337		assert!(!path.has_prefix("foo"));
338		assert!(path.has_prefix(Path::new("foobar")));
339	}
340
341	#[test]
342	fn test_strip_prefix() {
343		let path = Path::new("foo/bar/baz");
344
345		// Test with both &str and &Path
346		assert_eq!(path.strip_prefix("").unwrap().as_str(), "foo/bar/baz");
347		assert_eq!(path.strip_prefix("foo").unwrap().as_str(), "bar/baz");
348		assert_eq!(path.strip_prefix(Path::new("foo/")).unwrap().as_str(), "bar/baz");
349		assert_eq!(path.strip_prefix("foo/bar").unwrap().as_str(), "baz");
350		assert_eq!(path.strip_prefix(Path::new("foo/bar/")).unwrap().as_str(), "baz");
351		assert_eq!(path.strip_prefix("foo/bar/baz").unwrap().as_str(), "");
352
353		// Should fail for invalid prefixes
354		assert!(path.strip_prefix("fo").is_none());
355		assert!(path.strip_prefix(Path::new("bar")).is_none());
356	}
357
358	#[test]
359	fn test_join() {
360		// Test with both &str and &Path
361		assert_eq!(Path::new("foo").join("bar").as_str(), "foo/bar");
362		assert_eq!(Path::new("foo/").join(Path::new("bar")).as_str(), "foo/bar");
363		assert_eq!(Path::new("").join("bar").as_str(), "bar");
364		assert_eq!(Path::new("foo/bar").join(Path::new("baz")).as_str(), "foo/bar/baz");
365	}
366
367	#[test]
368	fn test_empty() {
369		let empty = Path::new("");
370		assert!(empty.is_empty());
371		assert_eq!(empty.len(), 0);
372
373		let non_empty = Path::new("foo");
374		assert!(!non_empty.is_empty());
375		assert_eq!(non_empty.len(), 3);
376	}
377
378	#[test]
379	fn test_from_conversions() {
380		let path1 = Path::from("foo/bar");
381		let path2 = Path::from("foo/bar");
382		let s = String::from("foo/bar");
383		let path3 = Path::from(&s);
384
385		assert_eq!(path1.as_str(), "foo/bar");
386		assert_eq!(path2.as_str(), "foo/bar");
387		assert_eq!(path3.as_str(), "foo/bar");
388	}
389
390	#[test]
391	fn test_path_prefix_join() {
392		let prefix = Path::new("foo");
393		let suffix = Path::new("bar/baz");
394		let path = prefix.join(&suffix);
395		assert_eq!(path.as_str(), "foo/bar/baz");
396
397		let prefix = Path::new("foo/");
398		let suffix = Path::new("bar/baz");
399		let path = prefix.join(&suffix);
400		assert_eq!(path.as_str(), "foo/bar/baz");
401
402		let prefix = Path::new("foo");
403		let suffix = Path::new("/bar/baz");
404		let path = prefix.join(&suffix);
405		assert_eq!(path.as_str(), "foo/bar/baz");
406
407		let prefix = Path::new("");
408		let suffix = Path::new("bar/baz");
409		let path = prefix.join(&suffix);
410		assert_eq!(path.as_str(), "bar/baz");
411	}
412
413	#[test]
414	fn test_path_prefix_conversions() {
415		let prefix1 = Path::from("foo/bar");
416		let prefix2 = Path::from(String::from("foo/bar"));
417		let s = String::from("foo/bar");
418		let prefix3 = Path::from(&s);
419
420		assert_eq!(prefix1.as_str(), "foo/bar");
421		assert_eq!(prefix2.as_str(), "foo/bar");
422		assert_eq!(prefix3.as_str(), "foo/bar");
423	}
424
425	#[test]
426	fn test_path_suffix_conversions() {
427		let suffix1 = Path::from("foo/bar");
428		let suffix2 = Path::from(String::from("foo/bar"));
429		let s = String::from("foo/bar");
430		let suffix3 = Path::from(&s);
431
432		assert_eq!(suffix1.as_str(), "foo/bar");
433		assert_eq!(suffix2.as_str(), "foo/bar");
434		assert_eq!(suffix3.as_str(), "foo/bar");
435	}
436
437	#[test]
438	fn test_path_types_basic_operations() {
439		let prefix = Path::new("foo/bar");
440		assert_eq!(prefix.as_str(), "foo/bar");
441		assert!(!prefix.is_empty());
442		assert_eq!(prefix.len(), 7);
443
444		let suffix = Path::new("baz/qux");
445		assert_eq!(suffix.as_str(), "baz/qux");
446		assert!(!suffix.is_empty());
447		assert_eq!(suffix.len(), 7);
448
449		let empty_prefix = Path::new("");
450		assert!(empty_prefix.is_empty());
451		assert_eq!(empty_prefix.len(), 0);
452
453		let empty_suffix = Path::new("");
454		assert!(empty_suffix.is_empty());
455		assert_eq!(empty_suffix.len(), 0);
456	}
457
458	#[test]
459	fn test_prefix_has_prefix() {
460		// Test empty prefix (should match everything)
461		let prefix = Path::new("foo/bar");
462		assert!(prefix.has_prefix(""));
463
464		// Test exact matches
465		let prefix = Path::new("foo/bar");
466		assert!(prefix.has_prefix("foo/bar"));
467
468		// Test valid prefixes
469		assert!(prefix.has_prefix("foo"));
470		assert!(prefix.has_prefix("foo/"));
471
472		// Test invalid prefixes - partial matches should fail
473		assert!(!prefix.has_prefix("f"));
474		assert!(!prefix.has_prefix("fo"));
475		assert!(!prefix.has_prefix("foo/b"));
476		assert!(!prefix.has_prefix("foo/ba"));
477
478		// Test edge cases
479		let prefix = Path::new("foobar");
480		assert!(!prefix.has_prefix("foo"));
481		assert!(prefix.has_prefix("foobar"));
482
483		// Test trailing slash handling
484		let prefix = Path::new("foo/bar/");
485		assert!(prefix.has_prefix("foo"));
486		assert!(prefix.has_prefix("foo/"));
487		assert!(prefix.has_prefix("foo/bar"));
488		assert!(prefix.has_prefix("foo/bar/"));
489
490		// Test single component
491		let prefix = Path::new("foo");
492		assert!(prefix.has_prefix(""));
493		assert!(prefix.has_prefix("foo"));
494		assert!(prefix.has_prefix("foo/")); // "foo/" becomes "foo" after trimming
495		assert!(!prefix.has_prefix("f"));
496
497		// Test empty prefix
498		let prefix = Path::new("");
499		assert!(prefix.has_prefix(""));
500		assert!(!prefix.has_prefix("foo"));
501	}
502
503	#[test]
504	fn test_prefix_join() {
505		// Basic joining
506		let prefix = Path::new("foo");
507		let suffix = Path::new("bar");
508		assert_eq!(prefix.join(suffix).as_str(), "foo/bar");
509
510		// Trailing slash on prefix
511		let prefix = Path::new("foo/");
512		let suffix = Path::new("bar");
513		assert_eq!(prefix.join(suffix).as_str(), "foo/bar");
514
515		// Leading slash on suffix
516		let prefix = Path::new("foo");
517		let suffix = Path::new("/bar");
518		assert_eq!(prefix.join(suffix).as_str(), "foo/bar");
519
520		// Trailing slash on suffix
521		let prefix = Path::new("foo");
522		let suffix = Path::new("bar/");
523		assert_eq!(prefix.join(suffix).as_str(), "foo/bar"); // trailing slash is trimmed
524
525		// Both have slashes
526		let prefix = Path::new("foo/");
527		let suffix = Path::new("/bar");
528		assert_eq!(prefix.join(suffix).as_str(), "foo/bar");
529
530		// Empty suffix
531		let prefix = Path::new("foo");
532		let suffix = Path::new("");
533		assert_eq!(prefix.join(suffix).as_str(), "foo");
534
535		// Empty prefix
536		let prefix = Path::new("");
537		let suffix = Path::new("bar");
538		assert_eq!(prefix.join(suffix).as_str(), "bar");
539
540		// Both empty
541		let prefix = Path::new("");
542		let suffix = Path::new("");
543		assert_eq!(prefix.join(suffix).as_str(), "");
544
545		// Complex paths
546		let prefix = Path::new("foo/bar");
547		let suffix = Path::new("baz/qux");
548		assert_eq!(prefix.join(suffix).as_str(), "foo/bar/baz/qux");
549
550		// Complex paths with slashes
551		let prefix = Path::new("foo/bar/");
552		let suffix = Path::new("/baz/qux/");
553		assert_eq!(prefix.join(suffix).as_str(), "foo/bar/baz/qux"); // all slashes are trimmed
554	}
555
556	#[test]
557	fn test_path_ref() {
558		// Test PathRef creation and normalization
559		let ref1 = Path::new("/foo/bar/");
560		assert_eq!(ref1.as_str(), "foo/bar");
561
562		let ref2 = Path::from("///foo///");
563		assert_eq!(ref2.as_str(), "foo");
564
565		// Test PathRef normalizes multiple slashes
566		let ref3 = Path::new("foo//bar///baz");
567		assert_eq!(ref3.as_str(), "foo/bar/baz");
568
569		// Test conversions
570		let path = Path::new("foo/bar");
571		let path_ref = path;
572		assert_eq!(path_ref.as_str(), "foo/bar");
573
574		// Test that Path methods work with PathRef
575		let path2 = Path::new("foo/bar/baz");
576		assert!(path2.has_prefix(&path_ref));
577		assert_eq!(path2.strip_prefix(path_ref).unwrap().as_str(), "baz");
578
579		// Test empty PathRef
580		let empty = Path::new("");
581		assert!(empty.is_empty());
582		assert_eq!(empty.len(), 0);
583	}
584
585	#[test]
586	fn test_multiple_consecutive_slashes() {
587		let path = Path::new("foo//bar///baz");
588		// Multiple consecutive slashes are collapsed to single slashes
589		assert_eq!(path.as_str(), "foo/bar/baz");
590
591		// Test with leading and trailing slashes too
592		let path2 = Path::new("//foo//bar///baz//");
593		assert_eq!(path2.as_str(), "foo/bar/baz");
594
595		// Test empty segments are handled correctly
596		let path3 = Path::new("foo///bar");
597		assert_eq!(path3.as_str(), "foo/bar");
598	}
599
600	#[test]
601	fn test_removes_multiple_slashes_comprehensively() {
602		// Test various multiple slash scenarios
603		assert_eq!(Path::new("foo//bar").as_str(), "foo/bar");
604		assert_eq!(Path::new("foo///bar").as_str(), "foo/bar");
605		assert_eq!(Path::new("foo////bar").as_str(), "foo/bar");
606
607		// Multiple occurrences of double slashes
608		assert_eq!(Path::new("foo//bar//baz").as_str(), "foo/bar/baz");
609		assert_eq!(Path::new("a//b//c//d").as_str(), "a/b/c/d");
610
611		// Mixed slash counts
612		assert_eq!(Path::new("foo//bar///baz////qux").as_str(), "foo/bar/baz/qux");
613
614		// With leading and trailing slashes
615		assert_eq!(Path::new("//foo//bar//").as_str(), "foo/bar");
616		assert_eq!(Path::new("///foo///bar///").as_str(), "foo/bar");
617
618		// Edge case: only slashes
619		assert_eq!(Path::new("//").as_str(), "");
620		assert_eq!(Path::new("////").as_str(), "");
621
622		// Test that operations work correctly with normalized paths
623		let path_with_slashes = Path::new("foo//bar///baz");
624		assert!(path_with_slashes.has_prefix("foo/bar"));
625		assert_eq!(path_with_slashes.strip_prefix("foo").unwrap().as_str(), "bar/baz");
626		assert_eq!(path_with_slashes.join("qux").as_str(), "foo/bar/baz/qux");
627
628		// Test PathRef to Path conversion
629		let path_ref = Path::new("foo//bar///baz");
630		assert_eq!(path_ref.as_str(), "foo/bar/baz"); // PathRef now normalizes too
631		let path_from_ref = path_ref.to_owned();
632		assert_eq!(path_from_ref.as_str(), "foo/bar/baz"); // Both are normalized
633	}
634
635	#[test]
636	fn test_path_ref_multiple_slashes() {
637		// PathRef now normalizes multiple slashes using Cow
638		let path_ref = Path::new("//foo//bar///baz//");
639		assert_eq!(path_ref.as_str(), "foo/bar/baz"); // Fully normalized
640
641		// Various multiple slash scenarios are normalized in PathRef
642		assert_eq!(Path::new("foo//bar").as_str(), "foo/bar");
643		assert_eq!(Path::new("foo///bar").as_str(), "foo/bar");
644		assert_eq!(Path::new("a//b//c//d").as_str(), "a/b/c/d");
645
646		// Conversion to Path maintains normalized form
647		assert_eq!(Path::new("foo//bar").to_owned().as_str(), "foo/bar");
648		assert_eq!(Path::new("foo///bar").to_owned().as_str(), "foo/bar");
649		assert_eq!(Path::new("a//b//c//d").to_owned().as_str(), "a/b/c/d");
650
651		// Edge cases
652		assert_eq!(Path::new("//").as_str(), "");
653		assert_eq!(Path::new("////").as_str(), "");
654		assert_eq!(Path::new("//").to_owned().as_str(), "");
655		assert_eq!(Path::new("////").to_owned().as_str(), "");
656
657		// Test that PathRef avoids allocation when no normalization needed
658		let normal_path = Path::new("foo/bar/baz");
659		assert_eq!(normal_path.as_str(), "foo/bar/baz");
660		// This should use Cow::Borrowed internally (no allocation)
661
662		let needs_norm = Path::new("foo//bar");
663		assert_eq!(needs_norm.as_str(), "foo/bar");
664		// This should use Cow::Owned internally (allocation only when needed)
665	}
666
667	#[test]
668	fn test_ergonomic_conversions() {
669		// Test that all these work ergonomically in function calls
670		fn takes_path_ref<'a>(p: impl Into<Path<'a>>) -> String {
671			p.into().as_str().to_string()
672		}
673
674		// Alternative API using the trait alias for better error messages
675		fn takes_path_ref_with_trait<'a>(p: impl Into<Path<'a>>) -> String {
676			p.into().as_str().to_string()
677		}
678
679		// String literal
680		assert_eq!(takes_path_ref("foo//bar"), "foo/bar");
681
682		// String (owned) - this should now work without &
683		let owned_string = String::from("foo//bar///baz");
684		assert_eq!(takes_path_ref(owned_string), "foo/bar/baz");
685
686		// &String
687		let string_ref = String::from("foo//bar");
688		assert_eq!(takes_path_ref(string_ref), "foo/bar");
689
690		// PathRef
691		let path_ref = Path::new("foo//bar");
692		assert_eq!(takes_path_ref(path_ref), "foo/bar");
693
694		// Path
695		let path = Path::new("foo//bar");
696		assert_eq!(takes_path_ref(path), "foo/bar");
697
698		// Test that Path::new works with all these types
699		let _path1 = Path::new("foo/bar"); // &str
700		let _path2 = Path::new("foo/bar"); // String - should now work
701		let _path3 = Path::new("foo/bar"); // &String
702		let _path4 = Path::new("foo/bar"); // PathRef
703
704		// Test the trait alias version works the same
705		assert_eq!(takes_path_ref_with_trait("foo//bar"), "foo/bar");
706		assert_eq!(takes_path_ref_with_trait(String::from("foo//bar")), "foo/bar");
707	}
708
709	#[test]
710	fn test_prefix_strip_prefix() {
711		// Test basic stripping
712		let prefix = Path::new("foo/bar/baz");
713		assert_eq!(prefix.strip_prefix("").unwrap().as_str(), "foo/bar/baz");
714		assert_eq!(prefix.strip_prefix("foo").unwrap().as_str(), "bar/baz");
715		assert_eq!(prefix.strip_prefix("foo/").unwrap().as_str(), "bar/baz");
716		assert_eq!(prefix.strip_prefix("foo/bar").unwrap().as_str(), "baz");
717		assert_eq!(prefix.strip_prefix("foo/bar/").unwrap().as_str(), "baz");
718		assert_eq!(prefix.strip_prefix("foo/bar/baz").unwrap().as_str(), "");
719
720		// Test invalid prefixes
721		assert!(prefix.strip_prefix("fo").is_none());
722		assert!(prefix.strip_prefix("bar").is_none());
723		assert!(prefix.strip_prefix("foo/ba").is_none());
724
725		// Test edge cases
726		let prefix = Path::new("foobar");
727		assert!(prefix.strip_prefix("foo").is_none());
728		assert_eq!(prefix.strip_prefix("foobar").unwrap().as_str(), "");
729
730		// Test empty prefix
731		let prefix = Path::new("");
732		assert_eq!(prefix.strip_prefix("").unwrap().as_str(), "");
733		assert!(prefix.strip_prefix("foo").is_none());
734
735		// Test single component
736		let prefix = Path::new("foo");
737		assert_eq!(prefix.strip_prefix("foo").unwrap().as_str(), "");
738		assert_eq!(prefix.strip_prefix("foo/").unwrap().as_str(), ""); // "foo/" becomes "foo" after trimming
739
740		// Test trailing slash handling
741		let prefix = Path::new("foo/bar/");
742		assert_eq!(prefix.strip_prefix("foo").unwrap().as_str(), "bar");
743		assert_eq!(prefix.strip_prefix("foo/").unwrap().as_str(), "bar");
744		assert_eq!(prefix.strip_prefix("foo/bar").unwrap().as_str(), "");
745		assert_eq!(prefix.strip_prefix("foo/bar/").unwrap().as_str(), "");
746	}
747}