windows_result/
bstr.rs

1use super::*;
2use core::ops::Deref;
3
4#[repr(transparent)]
5pub struct BasicString(*const u16);
6
7impl Deref for BasicString {
8    type Target = [u16];
9
10    fn deref(&self) -> &[u16] {
11        let len = if self.0.is_null() {
12            0
13        } else {
14            unsafe { SysStringLen(self.0) as usize }
15        };
16
17        if len > 0 {
18            unsafe { core::slice::from_raw_parts(self.0, len) }
19        } else {
20            // This ensures that if `as_ptr` is called on the slice that the resulting pointer
21            // will still refer to a null-terminated string.
22            const EMPTY: [u16; 1] = [0];
23            &EMPTY[..0]
24        }
25    }
26}
27
28impl Default for BasicString {
29    fn default() -> Self {
30        Self(core::ptr::null_mut())
31    }
32}
33
34impl Drop for BasicString {
35    fn drop(&mut self) {
36        if !self.0.is_null() {
37            unsafe { SysFreeString(self.0) }
38        }
39    }
40}