#![allow(unsafe_code)]
use std::ffi::OsStr;
use std::io;
use std::os::windows::ffi::OsStrExt;
pub(crate) fn wide_null(value: impl AsRef<OsStr>) -> io::Result<Vec<u16>> {
let mut units: Vec<u16> = value.as_ref().encode_wide().collect();
if units.contains(&0) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"string contains an interior NUL",
));
}
units.push(0);
Ok(units)
}
pub(crate) unsafe fn bounded_units<'a>(pointer: *const u16, maximum: usize) -> Option<&'a [u16]> {
if pointer.is_null() {
return None;
}
let mut length = 0_usize;
while length < maximum {
let unit = pointer.wrapping_add(length);
if unsafe { *unit } == 0 {
break;
}
length += 1;
}
if length == maximum {
return None;
}
Some(unsafe { std::slice::from_raw_parts(pointer, length) })
}
pub(crate) unsafe fn bounded_string(pointer: *const u16, maximum: usize) -> Option<String> {
unsafe { bounded_units(pointer, maximum) }.and_then(|units| String::from_utf16(units).ok())
}
#[cfg(test)]
mod tests {
use super::{bounded_units, wide_null};
#[test]
fn bounded_reads_stop_at_the_terminator_and_reject_missing_ones() {
let terminated: Vec<u16> = "abc".encode_utf16().chain(Some(0)).collect();
let read = unsafe { bounded_units(terminated.as_ptr(), 8) }.unwrap();
assert_eq!(String::from_utf16_lossy(read), "abc");
let unterminated: Vec<u16> = "abcd".encode_utf16().collect();
assert!(unsafe { bounded_units(unterminated.as_ptr(), 4) }.is_none());
assert!(unsafe { bounded_units(std::ptr::null(), 4) }.is_none());
}
#[test]
fn wide_null_appends_a_terminator_and_rejects_interior_nuls() {
assert_eq!(wide_null("x").unwrap(), [u16::from(b'x'), 0]);
assert!(wide_null("a\0b").is_err());
}
}