| 1 |
use super::*; |
| 2 |
|
| 3 |
/// An [HSTRING] builder that supports preallocating the `HSTRING` to avoid extra allocations and copies. |
| 4 |
/// |
| 5 |
/// This is similar to the `WindowsPreallocateStringBuffer` function but implemented directly in Rust for efficiency. |
| 6 |
/// It is implemented as a separate type since [HSTRING] values are immutable. |
| 7 |
pub struct HStringBuilder(*mut HStringHeader); |
| 8 |
|
| 9 |
impl HStringBuilder { |
| 10 |
/// Creates a preallocated `HSTRING` value. |
| 11 |
pub fn new(len: usize) -> Result<Self> { |
| 12 |
let header = HStringHeader::alloc(len.try_into()?)?; |
| 13 |
|
| 14 |
if len > 0 { |
| 15 |
unsafe { core::ptr::write_bytes((*header).data, 0, len) }; |
| 16 |
} |
| 17 |
|
| 18 |
Ok(Self(header)) |
| 19 |
} |
| 20 |
|
| 21 |
/// Shortens the string by removing any trailing 0 characters. |
| 22 |
pub fn trim_end(&mut self) { |
| 23 |
if let Some(header) = self.as_header_mut() { |
| 24 |
while header.len > 0 |
| 25 |
&& unsafe { header.data.offset(header.len as isize - 1).read() == 0 } |
| 26 |
{ |
| 27 |
header.len -= 1; |
| 28 |
} |
| 29 |
|
| 30 |
if header.len == 0 { |
| 31 |
unsafe { |
| 32 |
HStringHeader::free(self.0); |
| 33 |
} |
| 34 |
self.0 = core::ptr::null_mut(); |
| 35 |
} |
| 36 |
} |
| 37 |
} |
| 38 |
|
| 39 |
fn as_header(&self) -> Option<&HStringHeader> { |
| 40 |
unsafe { self.0.as_ref() } |
| 41 |
} |
| 42 |
|
| 43 |
fn as_header_mut(&mut self) -> Option<&mut HStringHeader> { |
| 44 |
unsafe { self.0.as_mut() } |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
impl From<HStringBuilder> for HSTRING { |
| 49 |
fn from(value: HStringBuilder) -> Self { |
| 50 |
if let Some(header) = value.as_header() { |
| 51 |
unsafe { header.data.offset(header.len as isize).write(0) }; |
| 52 |
let result = Self(value.0); |
| 53 |
core::mem::forget(value); |
| 54 |
result |
| 55 |
} else { |
| 56 |
Self::new() |
| 57 |
} |
| 58 |
} |
| 59 |
} |
| 60 |
|
| 61 |
impl core::ops::Deref for HStringBuilder { |
| 62 |
type Target = [u16]; |
| 63 |
|
| 64 |
fn deref(&self) -> &[u16] { |
| 65 |
if let Some(header) = self.as_header() { |
| 66 |
unsafe { core::slice::from_raw_parts(header.data, header.len as usize) } |
| 67 |
} else { |
| 68 |
&[] |
| 69 |
} |
| 70 |
} |
| 71 |
} |
| 72 |
|
| 73 |
impl core::ops::DerefMut for HStringBuilder { |
| 74 |
fn deref_mut(&mut self) -> &mut [u16] { |
| 75 |
if let Some(header) = self.as_header() { |
| 76 |
unsafe { core::slice::from_raw_parts_mut(header.data, header.len as usize) } |
| 77 |
} else { |
| 78 |
&mut [] |
| 79 |
} |
| 80 |
} |
| 81 |
} |
| 82 |
|
| 83 |
impl Drop for HStringBuilder { |
| 84 |
fn drop(&mut self) { |
| 85 |
unsafe { |
| 86 |
HStringHeader::free(self.0); |
| 87 |
} |
| 88 |
} |
| 89 |
} |