artifactize-foundation 0.27.1

Native file, path and executable primitives for Artifactize.
Documentation
use std::{
    ffi::{CStr, OsStr, OsString},
    io,
    mem::MaybeUninit,
    os::fd::AsRawFd,
    path::Path,
    ptr,
};

use core_foundation_sys::{
    base::CFRelease,
    string::{
        CFMutableStringRef, CFStringAppendCharacters, CFStringCreateMutable, CFStringFold,
        CFStringGetCharacters, CFStringGetLength, CFStringNormalize, kCFCompareCaseInsensitive,
        kCFStringNormalizationFormD,
    },
};

use super::NamePolicy;

pub(super) fn name_policy(path: &Path) -> io::Result<NamePolicy> {
    let directory = super::super::private::macos::open_directory_for_acl(path)?;
    if !super::super::files::case_sensitive(&directory)? {
        return Ok(NamePolicy::Folded);
    }
    let mut volume = MaybeUninit::<libc::statfs>::uninit();
    // SAFETY: the open directory and writable statfs buffer remain live; on success
    // fstatfs initializes the fixed struct, including its NUL-terminated type name.
    let apfs = unsafe {
        if libc::fstatfs(directory.as_raw_fd(), volume.as_mut_ptr()) != 0 {
            return Err(io::Error::last_os_error());
        }
        CStr::from_ptr(volume.assume_init().f_fstypename.as_ptr()) == c"apfs"
    };
    // Case-sensitive APFS still aliases canonically equivalent Unicode spellings.
    // Do not infer that normalization policy for other case-sensitive mounts.
    Ok(if apfs {
        NamePolicy::Decomposed
    } else {
        NamePolicy::Literal
    })
}

struct StringRef(CFMutableStringRef);

impl Drop for StringRef {
    fn drop(&mut self) {
        // SAFETY: the non-null reference was created and is owned here.
        unsafe { CFRelease(self.0.cast()) };
    }
}

pub(super) fn key(name: &OsStr, fold_case: bool) -> io::Result<OsString> {
    let Some(name) = name.to_str() else {
        // Preserve opaque Unix bytes rather than conflating malformed names.
        return Ok(name.to_owned());
    };
    let utf16: Vec<_> = name.encode_utf16().collect();
    // SAFETY: use the default allocator and an unrestricted mutable string.
    let text = unsafe { CFStringCreateMutable(ptr::null(), 0) };
    if text.is_null() {
        return Err(io::ErrorKind::OutOfMemory.into());
    }
    let text = StringRef(text);
    // SAFETY: the input buffer and mutable string are live. A null locale asks for
    // locale-independent case folding, even when the user's language changes.
    unsafe {
        CFStringAppendCharacters(text.0, utf16.as_ptr(), utf16.len() as isize);
        // APFS and HFS+ compare canonical equivalents. Case folding alone is not
        // a canonical decomposition, and diacritic-insensitive folding loses accents.
        CFStringNormalize(text.0, kCFStringNormalizationFormD);
        if fold_case {
            CFStringFold(text.0, kCFCompareCaseInsensitive, ptr::null());
        }
    }
    // SAFETY: the owned string remains live and the output is exactly its UTF-16 length.
    let length = unsafe { CFStringGetLength(text.0) };
    let mut folded = vec![0; length as usize];
    unsafe {
        CFStringGetCharacters(
            text.0,
            core_foundation_sys::base::CFRange {
                location: 0,
                length,
            },
            folded.as_mut_ptr(),
        );
    }
    String::from_utf16(&folded)
        .map(OsString::from)
        .map_err(io::Error::other)
}