use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};
use super::{is_absolute_name, split_drive};
use crate::error::Error;
pub(crate) enum DriveBase<'a> {
Cwd(&'a Path),
Drive(PathBuf),
}
impl DriveBase<'_> {
pub(crate) fn path(&self) -> &Path {
match self {
DriveBase::Cwd(cwd) => cwd,
DriveBase::Drive(dir) => dir,
}
}
}
pub(crate) fn drive_base<'a, 'n>(
name: &'n OsStr,
cwd: &'a Path,
same_drive: &dyn Fn(&OsStr, &OsStr) -> bool,
drive_dir: impl FnOnce(&OsStr) -> Result<Option<OsString>, Error>,
) -> Result<(DriveBase<'a>, &'n OsStr), Error> {
debug_assert!(
super::path_type(name) == super::PathType::DriveRelative,
"{name:?} is not drive-relative"
);
let (drive, rest) = split_drive(name).expect("a drive-relative path has a drive");
if split_drive(cwd.as_os_str()).is_some_and(|(d, _)| same_drive(d, drive)) {
return Ok((DriveBase::Cwd(cwd), rest));
}
let base = match drive_dir(drive)? {
Some(dir) => {
debug_assert!(
is_absolute_name(&dir, true),
"the directory of {drive:?} must be fully qualified: {dir:?}"
);
dir
}
None => {
let mut root = drive.to_os_string();
root.push("\\");
root
}
};
Ok((DriveBase::Drive(PathBuf::from(base)), rest))
}
#[cfg(test)]
#[path = "drive_relative_tests.rs"]
mod drive_relative_tests;