rustduck-core 1.1.0

Safe typed TSDuck core bindings for rustduck
Documentation
//! UTF-16 conversion at the safe/native boundary.

/// Encodes one TSDuck ABI string with its required UTF-16 BOM.
pub(crate) fn encode_utf16(value: &str) -> Vec<u8> {
    let mut units = Vec::with_capacity(value.len().saturating_add(1));
    units.push(0xfeff);
    units.extend(value.encode_utf16());

    let mut bytes = Vec::with_capacity(units.len() * size_of::<u16>());
    for unit in units {
        bytes.extend(unit.to_ne_bytes());
    }
    bytes
}

/// Decodes a complete UTF-16 byte buffer returned by the native boundary.
pub(crate) fn decode_utf16(operation: &'static str, bytes: &[u8]) -> crate::Result<String> {
    let chunks = bytes.chunks_exact(size_of::<u16>());
    if !chunks.remainder().is_empty() {
        return Err(crate::Error::NativeFailure { operation });
    }
    let units = chunks
        .map(|chunk| u16::from_ne_bytes([chunk[0], chunk[1]]))
        .skip_while(|unit| *unit == 0xfeff)
        .collect::<Vec<_>>();
    String::from_utf16(&units).map_err(|_| crate::Error::NativeFailure { operation })
}