Debian Codegraph @

third_party/rust/windows-strings/src/bstr.rs

raw
1 use super::*;
2
3 /// A BSTR string ([BSTR](https://learn.microsoft.com/en-us/previous-versions/windows/desktop/automat/string-manipulation-functions))
4 /// is a length-prefixed wide string.
5 #[repr(transparent)]
6 pub struct BSTR(*const u16);
7
8 impl BSTR {
9 /// Create an empty `BSTR`.
10 ///
11 /// This function does not allocate memory.
12 pub const fn new() -> Self {
13 Self(core::ptr::null_mut())
14 }
15
16 /// Returns `true` if the string is empty.
17 pub fn is_empty(&self) -> bool {
18 self.len() == 0
19 }
20
21 /// Returns the length of the string.
22 pub fn len(&self) -> usize {
23 if self.0.is_null() {
24 0
25 } else {
26 unsafe { bindings::SysStringLen(self.0) as usize }
27 }
28 }
29
30 /// Get the string as 16-bit wide characters (wchars).
31 pub fn as_wide(&self) -> &[u16] {
32 unsafe { core::slice::from_raw_parts(self.as_ptr(), self.len()) }
33 }
34
35 /// Returns a raw pointer to the `BSTR` buffer.
36 pub fn as_ptr(&self) -> *const u16 {
37 if !self.is_empty() {
38 self.0
39 } else {
40 const EMPTY: [u16; 1] = [0];
41 EMPTY.as_ptr()
42 }
43 }
44
45 /// Create a `BSTR` from a slice of 16 bit characters (wchars).
46 pub fn from_wide(value: &[u16]) -> Result<Self> {
47 if value.is_empty() {
48 return Ok(Self::new());
49 }
50
51 let result = unsafe {
52 Self(bindings::SysAllocStringLen(
53 value.as_ptr(),
54 value.len().try_into()?,
55 ))
56 };
57
58 if result.is_empty() {
59 Err(Error::from_hresult(HRESULT(bindings::E_OUTOFMEMORY)))
60 } else {
61 Ok(result)
62 }
63 }
64
65 /// # Safety
66 #[doc(hidden)]
67 pub unsafe fn from_raw(raw: *const u16) -> Self {
68 Self(raw)
69 }
70
71 /// # Safety
72 #[doc(hidden)]
73 pub fn into_raw(self) -> *const u16 {
74 unsafe { core::mem::transmute(self) }
75 }
76 }
77
78 impl Clone for BSTR {
79 fn clone(&self) -> Self {
80 Self::from_wide(self.as_wide()).unwrap()
81 }
82 }
83
84 impl From<&str> for BSTR {
85 fn from(value: &str) -> Self {
86 let value: alloc::vec::Vec<u16> = value.encode_utf16().collect();
87 Self::from_wide(&value).unwrap()
88 }
89 }
90
91 impl From<String> for BSTR {
92 fn from(value: String) -> Self {
93 value.as_str().into()
94 }
95 }
96
97 impl From<&String> for BSTR {
98 fn from(value: &String) -> Self {
99 value.as_str().into()
100 }
101 }
102
103 impl<'a> TryFrom<&'a BSTR> for String {
104 type Error = alloc::string::FromUtf16Error;
105
106 fn try_from(value: &BSTR) -> core::result::Result<Self, Self::Error> {
107 String::from_utf16(value.as_wide())
108 }
109 }
110
111 impl TryFrom<BSTR> for String {
112 type Error = alloc::string::FromUtf16Error;
113
114 fn try_from(value: BSTR) -> core::result::Result<Self, Self::Error> {
115 String::try_from(&value)
116 }
117 }
118
119 impl Default for BSTR {
120 fn default() -> Self {
121 Self(core::ptr::null_mut())
122 }
123 }
124
125 impl core::fmt::Display for BSTR {
126 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
127 core::write!(
128 f,
129 "{}",
130 Decode(|| core::char::decode_utf16(self.as_wide().iter().cloned()))
131 )
132 }
133 }
134
135 impl core::fmt::Debug for BSTR {
136 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
137 core::write!(f, "{}", self)
138 }
139 }
140
141 impl PartialEq for BSTR {
142 fn eq(&self, other: &Self) -> bool {
143 self.as_wide() == other.as_wide()
144 }
145 }
146
147 impl Eq for BSTR {}
148
149 impl PartialEq<BSTR> for &str {
150 fn eq(&self, other: &BSTR) -> bool {
151 other == self
152 }
153 }
154
155 impl PartialEq<BSTR> for String {
156 fn eq(&self, other: &BSTR) -> bool {
157 other == self
158 }
159 }
160
161 impl<T: AsRef<str> + ?Sized> PartialEq<T> for BSTR {
162 fn eq(&self, other: &T) -> bool {
163 self.as_wide()
164 .iter()
165 .copied()
166 .eq(other.as_ref().encode_utf16())
167 }
168 }
169
170 impl Drop for BSTR {
171 fn drop(&mut self) {
172 if !self.0.is_null() {
173 unsafe { bindings::SysFreeString(self.0) }
174 }
175 }
176 }