Skip to main content

yazi_shared/path/
cow.rs

1use std::borrow::Cow;
2
3use anyhow::Result;
4
5use crate::path::{AsPath, PathBufDyn, PathDyn, PathDynError, PathKind};
6
7#[derive(Debug)]
8pub enum PathCow<'a> {
9	Borrowed(PathDyn<'a>),
10	Owned(PathBufDyn),
11}
12
13impl<'a> From<PathDyn<'a>> for PathCow<'a> {
14	fn from(value: PathDyn<'a>) -> Self { Self::Borrowed(value) }
15}
16
17impl From<PathBufDyn> for PathCow<'_> {
18	fn from(value: PathBufDyn) -> Self { Self::Owned(value) }
19}
20
21impl<'a> From<std::path::PathBuf> for PathCow<'a> {
22	fn from(value: std::path::PathBuf) -> Self { Self::Owned(value.into()) }
23}
24
25impl<'a> From<&'a PathCow<'_>> for PathCow<'a> {
26	fn from(value: &'a PathCow<'_>) -> Self { Self::Borrowed(value.as_path()) }
27}
28
29impl From<PathCow<'_>> for PathBufDyn {
30	fn from(value: PathCow<'_>) -> Self { value.into_owned() }
31}
32
33impl PartialEq for PathCow<'_> {
34	fn eq(&self, other: &Self) -> bool { self.as_path() == other.as_path() }
35}
36
37impl PartialEq<&str> for PathCow<'_> {
38	fn eq(&self, other: &&str) -> bool {
39		match self {
40			Self::Borrowed(s) => s.as_path() == *other,
41			Self::Owned(s) => s.as_path() == *other,
42		}
43	}
44}
45
46impl<'a> PathCow<'a> {
47	pub fn into_encoded_bytes(self) -> Cow<'a, [u8]> {
48		match self {
49			Self::Borrowed(p) => Cow::Borrowed(p.encoded_bytes()),
50			Self::Owned(p) => Cow::Owned(p.into_encoded_bytes()),
51		}
52	}
53
54	pub fn into_owned(self) -> PathBufDyn {
55		match self {
56			Self::Borrowed(p) => p.to_owned(),
57			Self::Owned(p) => p,
58		}
59	}
60
61	pub fn into_os(self) -> Result<std::path::PathBuf, PathDynError> {
62		match self {
63			PathCow::Borrowed(p) => p.to_os_owned(),
64			PathCow::Owned(p) => p.into_os(),
65		}
66	}
67
68	pub fn is_borrowed(&self) -> bool { matches!(self, Self::Borrowed(_)) }
69
70	pub fn with<K, T>(kind: K, bytes: T) -> Result<Self>
71	where
72		K: Into<PathKind>,
73		T: Into<Cow<'a, [u8]>>,
74	{
75		Ok(match bytes.into() {
76			Cow::Borrowed(b) => PathDyn::with(kind, b)?.into(),
77			Cow::Owned(b) => PathBufDyn::with(kind, b)?.into(),
78		})
79	}
80}