Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 22 additions & 2 deletions crates/host_env/src/winreg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

extern crate alloc;

use alloc::string::FromUtf16Error;
use alloc::{borrow::Cow, string::FromUtf16Error};
use rustpython_wtf8::Wtf8Buf;

use windows_sys::Win32::{
Expand Down Expand Up @@ -97,6 +97,26 @@ pub fn bytes_as_wide_slice(bytes: &[u8]) -> &[u16] {
u16_slice
}

pub fn registry_wide_units(bytes: &[u8]) -> Cow<'_, [u16]> {
// Windows strings use complete native-endian UTF-16 code units; CPython
// ignores a trailing incomplete byte.
let bytes = &bytes[..bytes.len() & !1];
// SAFETY: Every u16 bit pattern is valid and align_to checks alignment.
let (prefix, u16_slice, _) = unsafe { bytes.align_to::<u16>() };
if prefix.is_empty() {
Cow::Borrowed(u16_slice)
} else {
Cow::Owned(
bytes
.as_chunks::<2>()
.0
.iter()
.map(|&pair| u16::from_ne_bytes(pair))
.collect(),
)
}
}

pub fn close_key(hkey: Registry::HKEY) -> u32 {
unsafe { Registry::RegCloseKey(hkey) }
}
Expand Down Expand Up @@ -423,7 +443,7 @@ fn query_default_value_with<T>(
break Err(QueryStringError::Code(Foundation::ERROR_INVALID_DATA));
}

let u16_slice = bytes_as_wide_slice(&buffer[..size as usize]);
let u16_slice = registry_wide_units(&buffer[..size as usize]);
let len = u16_slice
.iter()
.position(|&c| c == 0)
Expand Down
4 changes: 2 additions & 2 deletions crates/vm/src/stdlib/winreg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -758,7 +758,7 @@ mod winreg {
Ok(vm.ctx.new_int(val).into())
}
REG_SZ | REG_EXPAND_SZ => {
let u16_slice = host_winreg::bytes_as_wide_slice(ret_data);
let u16_slice = host_winreg::registry_wide_units(ret_data);
// Only use characters up to the first NUL.
let len = u16_slice
.iter()
Expand All @@ -772,7 +772,7 @@ mod winreg {
if ret_data.is_empty() {
Ok(vm.ctx.new_list(vec![]).into())
} else {
let u16_slice = host_winreg::bytes_as_wide_slice(ret_data);
let u16_slice = host_winreg::registry_wide_units(ret_data);
let u16_count = u16_slice.len();

// Remove trailing null if present (like countStrings)
Expand Down
Loading