cap_primitives/fs/manually/
cow_component.rs

1use std::borrow::Cow;
2use std::ffi::OsStr;
3use std::path::Component;
4
5/// Like `std::path::Component` except we combine `Prefix` and `RootDir` since
6/// we don't support absolute paths, and `Normal` has a `Cow` instead of a
7/// plain `OsStr` reference, so it can optionally own its own string.
8pub(super) enum CowComponent<'borrow> {
9    PrefixOrRootDir,
10    CurDir,
11    ParentDir,
12    Normal(Cow<'borrow, OsStr>),
13}
14
15impl<'borrow> CowComponent<'borrow> {
16    /// Convert a `Component` into a `CowComponent` which borrows strings.
17    pub(super) fn borrowed(component: Component<'borrow>) -> Self {
18        match component {
19            Component::Prefix(_) | Component::RootDir => Self::PrefixOrRootDir,
20            Component::CurDir => Self::CurDir,
21            Component::ParentDir => Self::ParentDir,
22            Component::Normal(os_str) => Self::Normal(os_str.into()),
23        }
24    }
25
26    /// Convert a `Component` into a `CowComponent` which owns strings.
27    pub(super) fn owned(component: Component) -> Self {
28        match component {
29            Component::Prefix(_) | Component::RootDir => Self::PrefixOrRootDir,
30            Component::CurDir => Self::CurDir,
31            Component::ParentDir => Self::ParentDir,
32            Component::Normal(os_str) => Self::Normal(os_str.to_os_string().into()),
33        }
34    }
35
36    /// Test whether `self` is `Component::Normal`.
37    #[cfg(windows)]
38    pub(super) fn is_normal(&self) -> bool {
39        match self {
40            CowComponent::Normal(_) => true,
41            _ => false,
42        }
43    }
44}