microsoft / windows-rs

Rust for Windows
https://kennykerr.ca/rust-getting-started/
Apache License 2.0
10.35k stars 486 forks source link

Add `HSTRING` builder and registry support #3133

Closed kennykerr closed 3 months ago

kennykerr commented 3 months ago

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 commented 3 months ago

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