1mod 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
20const INLINE: usize = size_of::<Arc<str>>() + size_of::<usize>() - 2;
23
24#[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);
37const _: () = assert!(Path::MAX_BYTES <= u16::MAX as usize);
39
40impl Repr {
41 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#[derive(Debug, Copy, Clone, Eq, PartialEq, thiserror::Error)]
62#[non_exhaustive]
63pub enum Error {
64 #[error("path is longer than {} bytes", Path::MAX_BYTES)]
66 TooLong,
67
68 #[error("path contains an empty segment")]
70 EmptySegment,
71
72 #[error(r"path contains a `\` that escapes neither `\` nor `/`")]
74 InvalidEscape,
75}
76
77fn 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 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 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 if s.ends_with('/') || s.contains("//") {
106 return Err(Error::EmptySegment);
107 }
108 match parts(s).any(str::is_empty) {
110 true => Err(Error::EmptySegment),
111 false => Ok(()),
112 }
113}
114
115#[derive(Clone)]
153pub struct Path(Repr);
154
155impl Path {
156 pub const MAX_PARTS: usize = 32;
162
163 pub const MAX_BYTES: usize = 4096;
168
169 pub fn new(s: &str) -> Result<Self, Error> {
176 validate(s)?;
177 Ok(Self(Repr::copy_bounded(s)))
178 }
179
180 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 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 start: *start + n as u16,
201 }),
202 _ => Path(Repr::copy_bounded(rest)),
203 }
204 }
205
206 pub fn has_prefix(&self, prefix: &Path) -> bool {
226 self.prefix_len(prefix).is_some()
227 }
228
229 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 if s.len() == prefix.len() {
243 return Some(s.len());
244 }
245
246 (s.as_bytes().get(prefix.len()) == Some(&b'/')).then_some(prefix.len() + 1)
248 }
249
250 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 pub fn head(&self, n: usize) -> Option<Path> {
274 let end = self.head_len(n)?;
275 let s = self.as_str();
276 Some(match &self.0 {
278 Repr::Static(s) => Path(Repr::Static(&s[..end])),
279 _ => Path(Repr::copy_bounded(&s[..end])),
280 })
281 }
282
283 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 pub(crate) fn depth(&self) -> usize {
301 self.as_str().split_terminator('/').count()
302 }
303
304 pub fn parts(&self) -> Parts<'_> {
318 parts(self.as_str())
321 }
322
323 pub(crate) fn is_hidden(&self) -> bool {
326 self.parts().any(|part| part.starts_with('.'))
327 }
328
329 pub fn as_str(&self) -> &str {
331 match &self.0 {
332 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 pub const fn empty() -> Path {
342 Path(Repr::Static(""))
343 }
344
345 pub fn is_empty(&self) -> bool {
347 self.as_str().is_empty()
348 }
349
350 pub fn len(&self) -> usize {
352 self.as_str().len()
353 }
354
355 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 pub(crate) fn rejoin(&self, other: &Path) -> Path {
384 self.join(other).expect("a rejoined path fits")
385 }
386
387 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 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 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 Path::new(&segments.join("/"))
455 }
456
457 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 pub fn relative(&self, base: &Path) -> Option<Relative> {
519 if self == base {
522 return Some(Relative::empty());
523 }
524
525 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 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 return Some(Relative(Path::from_static(".")));
544 }
545
546 Relative::new(&rel.join("/")).ok()
547 }
548}
549
550#[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
565pub(crate) fn convert<E>(path: impl TryInto<Path, Error: Into<E>>) -> Result<Path, E> {
567 path.try_into().map_err(Into::into)
568}
569
570impl 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
598impl 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 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 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
704impl<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 let mut prefixes = Vec::new();
721 for _ in 0..count {
722 let prefix = Prefix::try_from(r.string()?).map_err(|_| DecodeError::InvalidValue)?;
724 prefixes.push(prefix);
725 }
726 Ok(prefixes.into_iter().collect())
728 }
729}
730
731#[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 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 Ok(Self(Path::new(&normalize_relative_segments(&path))?))
783 }
784
785 pub fn as_str(&self) -> &str {
787 self.0.as_str()
788 }
789
790 pub const fn empty() -> Relative {
792 Relative(Path::empty())
793 }
794
795 pub fn is_empty(&self) -> bool {
797 self.0.is_empty()
798 }
799
800 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
830fn 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 assert!(Path::new("").unwrap().is_empty());
879 assert_eq!(Path::try_from(String::new()).unwrap(), Path::empty());
880
881 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 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 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 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 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 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 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 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 let long = p(&format!("{}/tail", "a".repeat(INLINE + 1)));
1005 assert_eq!(long.head(1).unwrap().as_str(), "a".repeat(INLINE + 1));
1006
1007 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 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 #[test]
1029 fn test_long_paths_share_allocation() {
1030 let path = Path::new("customer/room-0123456789/broadcast").unwrap();
1031
1032 let cloned = path.clone();
1034 assert_eq!(path.as_str().as_ptr(), cloned.as_str().as_ptr());
1035
1036 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 assert_eq!(rel("foo/bar/baz", "foo/bar").as_str(), "bar/baz");
1377 assert_eq!(rel("foo/baz", "foo/bar").as_str(), "baz");
1379 assert_eq!(rel("foo/baz/bar", "foo/bar/baz").as_str(), "../baz/bar");
1381 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 assert_eq!(rel("foo/bar", "").as_str(), "foo/bar");
1386 assert_eq!(rel("", "foo").as_str(), ".");
1387 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 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 assert_eq!(
1402 Path::from_static("a/..")
1403 .relative(&Path::from_static("a/.."))
1404 .unwrap()
1405 .as_str(),
1406 ""
1407 );
1408
1409 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 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 assert!(
1442 base.try_resolve(&rel).is_some(),
1443 "{base} -> {target} via {rel} escaped the root"
1444 );
1445 }
1446 }
1447 }
1448}