windows-strings 0.101.0

Windows string types
Documentation
use super::*;

/// Builder for preallocating immutable [`HSTRING`] values.
pub struct HStringBuilder(*mut HStringHeader);

impl HStringBuilder {
    /// Creates a preallocated `HSTRING` value.
    pub fn new(len: usize) -> Self {
        let header = HStringHeader::alloc(len.try_into().unwrap());

        if len > 0 {
            unsafe { core::ptr::write_bytes((*header).data, 0, len) };
        }

        Self(header)
    }

    /// Shortens the string by removing any trailing 0 characters.
    pub fn trim_end(&mut self) {
        let mut new_len = self.len();
        while new_len > 0 && self[new_len - 1] == 0 {
            new_len -= 1;
        }
        if new_len == 0 {
            unsafe {
                HStringHeader::free(self.0);
            }
            self.0 = core::ptr::null_mut();
        } else {
            unsafe { (*self.0).len = new_len as u32 };
        }
    }

    /// Returns the mutable UTF-16 buffer as bytes.
    pub fn as_bytes_mut(&mut self) -> &mut [u8] {
        if !self.0.is_null() {
            unsafe {
                core::slice::from_raw_parts_mut((*self.0).data.cast(), (*self.0).len as usize * 2)
            }
        } else {
            &mut []
        }
    }
}

impl From<HStringBuilder> for HSTRING {
    fn from(value: HStringBuilder) -> Self {
        if !value.0.is_null() {
            unsafe { (*value.0).data.add((*value.0).len as usize).write(0) };
            let result = Self(value.0);
            core::mem::forget(value);
            result
        } else {
            Self::new()
        }
    }
}

impl core::ops::Deref for HStringBuilder {
    type Target = [u16];

    fn deref(&self) -> &[u16] {
        if !self.0.is_null() {
            unsafe { core::slice::from_raw_parts((*self.0).data, (*self.0).len as usize) }
        } else {
            &[]
        }
    }
}

impl core::ops::DerefMut for HStringBuilder {
    fn deref_mut(&mut self) -> &mut [u16] {
        if !self.0.is_null() {
            unsafe { core::slice::from_raw_parts_mut((*self.0).data, (*self.0).len as usize) }
        } else {
            &mut []
        }
    }
}

impl Drop for HStringBuilder {
    fn drop(&mut self) {
        unsafe {
            HStringHeader::free(self.0);
        }
    }
}

impl core::fmt::Debug for HStringBuilder {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        write!(
            f,
            "\"{}\"",
            Decode(|| core::char::decode_utf16(self.iter().copied()))
        )
    }
}