fn utf8_from_cfstringref()

in coreaudio-sys-utils/src/string.rs [82:129]


fn utf8_from_cfstringref(string_ref: CFStringRef) -> Vec<u8> {
    use std::ptr;

    assert!(!string_ref.is_null());

    let length: CFIndex = unsafe { CFStringGetLength(string_ref) };
    if length == 0 {
        return Vec::new();
    }

    // Get the buffer size of the string.
    let range: CFRange = CFRange {
        location: 0,
        length,
    };
    let mut size: CFIndex = 0;
    let mut converted_chars: CFIndex = unsafe {
        CFStringGetBytes(
            string_ref,
            range,
            kCFStringEncodingUTF8,
            0,
            false as Boolean,
            ptr::null_mut(),
            0,
            &mut size,
        )
    };
    assert!(converted_chars > 0 && size > 0);

    // Then, allocate the buffer with the required size and actually copy data into it.
    let mut buffer = vec![b'\x00'; size as usize];
    converted_chars = unsafe {
        CFStringGetBytes(
            string_ref,
            range,
            kCFStringEncodingUTF8,
            0,
            false as Boolean,
            buffer.as_mut_ptr(),
            size,
            ptr::null_mut() as *mut CFIndex,
        )
    };
    assert!(converted_chars > 0);

    buffer
}