Skip to content

Add HSTRING builder and registry support - #3133

Merged
Kenny Kerr (kennykerr) merged 4 commits into
masterfrom
hstring-builder
Jun 28, 2024
Merged

Kenny Kerr (kennykerr) merged 4 commits into
masterfrom
hstring-builder

Conversation

@kennykerr

@kennykerr Kenny Kerr (kennykerr) commented Jun 27, 2024 •

Copy link
Copy Markdown
Collaborator

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
Copy Markdown
Collaborator Author

Thanks to Rafael Rivera (@riverar) for helping me fix that natvis... again. 😂

Comment thread crates/libs/strings/src/hstring.rs Resolved
Comment thread crates/libs/strings/src/hstring.rs Resolved
Comment thread crates/libs/registry/src/key.rs Resolved
@kennykerr
Kenny Kerr (kennykerr) merged commit 62ccc94 into master Jun 28, 2024
@kennykerr
Kenny Kerr (kennykerr) deleted the hstring-builder branch June 28, 2024 19:44

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
Copy Markdown
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
Copy Markdown
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?

4 participants