use crate::filesystem::primitives::{OpenOptions, open_unchecked};
use std::ops::Deref;
use std::path::Component;
use std::{fmt, fs, io, mem};
pub(super) enum MaybeOwnedFile<'borrow> {
Borrowed(&'borrow fs::File),
Owned(fs::File),
}
impl<'borrow> MaybeOwnedFile<'borrow> {
pub(super) fn borrowed(file: &'borrow fs::File) -> Self {
Self::Borrowed(file)
}
pub(super) fn owned(file: fs::File) -> Self {
Self::Owned(file)
}
pub(super) fn descend_to(&mut self, to: MaybeOwnedFile<'borrow>) -> Self {
mem::replace(self, to)
}
#[cfg_attr(windows, allow(dead_code))]
pub(super) fn into_file(self, options: &OpenOptions) -> io::Result<fs::File> {
match self {
Self::Owned(file) => Ok(file),
Self::Borrowed(file) => {
open_unchecked(file, Component::CurDir.as_ref(), options).map_err(Into::into)
}
}
}
}
impl<'borrow> Deref for MaybeOwnedFile<'borrow> {
type Target = fs::File;
#[inline]
fn deref(&self) -> &Self::Target {
match self {
Self::Borrowed(file) => file,
Self::Owned(file) => file,
}
}
}
impl<'borrow> fmt::Debug for MaybeOwnedFile<'borrow> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.deref().fmt(f)
}
}