Skip to content

Conversation

@kennykerr
Copy link
Collaborator

@kennykerr kennykerr commented Jun 27, 2024

This update adds two features to improve string support and efficiency.

The HSTRING type now includes an HStringBuilder type for pre-allocating and constructing an HSTRING without requiring an additional copy. This is similar to the WindowsPreallocateStringBuffer function but implemented directly in Rust, as I did for C++/WinRT back in the day.

const HELLO: [u16; 5] = [0x48, 0x65, 0x6C, 0x6C, 0x6F];
let mut b = HStringBuilder::new(5)?;
b.copy_from_slice(&HELLO);
let h: HSTRING = b.into();
assert_eq!(&h, "Hello");

The windows-registry crate now also provide get_hstring and set_hstring for reading and writing registry values using HSTRING. This is far more efficient than either String or OsString and is lossless, while still providing convertibility with String and OsString.

key.set_hstring("key", h!("value"))?;
let value: HSTRING = key.get_hstring("key")?;
key.set_hstring("key", &value)?;

Fixes: #3119

@kennykerr
Copy link
Collaborator Author

Thanks to @riverar for helping me fix that natvis... again. 😂

@kennykerr kennykerr requested review from ChrisDenton and riverar June 27, 2024 19:27
@kennykerr kennykerr merged commit 62ccc94 into master Jun 28, 2024
@kennykerr kennykerr deleted the hstring-builder branch June 28, 2024 19:44
@kennykerr kennykerr mentioned this pull request Jul 2, 2024

fn deref(&self) -> &[u16] {
if let Some(header) = self.as_header() {
unsafe { core::slice::from_raw_parts(header.data, header.len as usize) }
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doesn't this expose uninitialized memory? i.e. *HStringBuilder::new(123).unwrap() is a [u16] slice whose contents are uninitialized.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, thanks for the reminder: #3141

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Should windows_registry::Key::(get|set)_string use OsStr instead of str?

5 participants