use std::{
ffi::{OsStr, OsString},
fs::OpenOptions,
io,
os::windows::{
ffi::{OsStrExt, OsStringExt},
fs::OpenOptionsExt,
io::AsRawHandle,
},
path::Path,
};
use windows_sys::{
Wdk::System::SystemServices::RtlUpcaseUnicodeChar,
Win32::{
Foundation::{ERROR_INVALID_FUNCTION, ERROR_INVALID_PARAMETER, ERROR_NOT_SUPPORTED},
Storage::FileSystem::{
FILE_CASE_SENSITIVE_INFO, FILE_READ_ATTRIBUTES, FileCaseSensitiveInfo,
GetFileInformationByHandleEx,
},
System::SystemServices::FILE_CS_FLAG_CASE_SENSITIVE_DIR,
},
};
use super::NamePolicy;
pub(super) fn name_policy(path: &Path) -> io::Result<NamePolicy> {
case_sensitive(path).map(|sensitive| {
if sensitive {
NamePolicy::Literal
} else {
NamePolicy::Folded
}
})
}
fn case_sensitive(path: &Path) -> io::Result<bool> {
let directory = super::super::files::open_no_follow(
OpenOptions::new().access_mode(FILE_READ_ATTRIBUTES),
path,
)?;
let mut info = FILE_CASE_SENSITIVE_INFO::default();
if unsafe {
GetFileInformationByHandleEx(
directory.as_raw_handle(),
FileCaseSensitiveInfo,
(&raw mut info).cast(),
std::mem::size_of_val(&info) as u32,
)
} != 0
{
return Ok(info.Flags & FILE_CS_FLAG_CASE_SENSITIVE_DIR != 0);
}
let error = io::Error::last_os_error();
match error.raw_os_error().map(|code| code as u32) {
Some(ERROR_INVALID_FUNCTION | ERROR_INVALID_PARAMETER | ERROR_NOT_SUPPORTED) => Ok(false),
_ => Err(error),
}
}
pub(super) fn fold(name: &OsStr) -> OsString {
let upper: Vec<u16> = name
.encode_wide()
.map(|unit| unsafe { RtlUpcaseUnicodeChar(unit) })
.collect();
OsString::from_wide(&upper)
}