Skip to main content

windows_strings/
hstring.rs

1use super::*;
2use core::ops::Deref;
3
4/// An ([HSTRING](https://docs.microsoft.com/en-us/windows/win32/winrt/hstring))
5/// is a reference-counted and immutable UTF-16 string type.
6#[repr(transparent)]
7pub struct HSTRING(pub(crate) *mut HStringHeader);
8
9impl HSTRING {
10    /// Creates an empty `HSTRING` without allocating.
11    pub const fn new() -> Self {
12        Self(core::ptr::null_mut())
13    }
14
15    /// Creates an `HSTRING` from UTF-16 code units.
16    pub fn from_wide(value: &[u16]) -> Self {
17        unsafe { Self::from_wide_iter(value.iter().copied(), value.len()) }
18    }
19
20    /// Returns a pointer to the UTF-16 buffer, including its trailing null terminator.
21    ///
22    /// The pointer remains valid while this string is alive, including for an empty string.
23    pub fn as_ptr(&self) -> *const u16 {
24        if let Some(header) = self.as_header() {
25            header.data
26        } else {
27            const EMPTY: [u16; 1] = [0];
28            EMPTY.as_ptr()
29        }
30    }
31
32    /// Converts the string to a lossy UTF-8 `String`.
33    pub fn to_string_lossy(&self) -> String {
34        String::from_utf16_lossy(self)
35    }
36
37    /// Converts the string to an `OsString`.
38    #[cfg(all(feature = "std", windows))]
39    pub fn to_os_string(&self) -> std::ffi::OsString {
40        std::os::windows::ffi::OsStringExt::from_wide(self)
41    }
42
43    /// Returns a display adapter for the string.
44    pub fn display(&self) -> impl core::fmt::Display + '_ {
45        Decode(move || core::char::decode_utf16(self.iter().copied()))
46    }
47
48    /// # Safety
49    /// `len` must not be less than the number of items in `iter`.
50    unsafe fn from_wide_iter<I: Iterator<Item = u16>>(iter: I, len: usize) -> Self {
51        if len == 0 {
52            return Self::new();
53        }
54
55        let ptr = HStringHeader::alloc(len.try_into().unwrap());
56
57        for (index, wide) in iter.enumerate() {
58            debug_assert!(index < len);
59
60            unsafe {
61                (*ptr).data.add(index).write(wide);
62                (*ptr).len = index as u32 + 1;
63            }
64        }
65
66        unsafe {
67            (*ptr).data.offset((*ptr).len as isize).write(0);
68        }
69        Self(ptr)
70    }
71
72    fn as_header(&self) -> Option<&HStringHeader> {
73        unsafe { self.0.as_ref() }
74    }
75}
76
77impl Deref for HSTRING {
78    type Target = [u16];
79
80    fn deref(&self) -> &[u16] {
81        if let Some(header) = self.as_header() {
82            unsafe { core::slice::from_raw_parts(header.data, header.len as usize) }
83        } else {
84            const EMPTY: [u16; 1] = [0];
85            &EMPTY[..0]
86        }
87    }
88}
89
90impl Default for HSTRING {
91    fn default() -> Self {
92        Self::new()
93    }
94}
95
96impl Clone for HSTRING {
97    fn clone(&self) -> Self {
98        unsafe { Self(HStringHeader::duplicate(self.0)) }
99    }
100}
101
102impl Drop for HSTRING {
103    fn drop(&mut self) {
104        if let Some(header) = self.as_header() {
105            // Fast-pass strings are borrowed and not reference-counted.
106            unsafe {
107                if header.flags & HSTRING_REFERENCE_FLAG == 0 && header.count.release() == 0 {
108                    HStringHeader::free(self.0);
109                }
110            }
111        }
112    }
113}
114
115unsafe impl Send for HSTRING {}
116unsafe impl Sync for HSTRING {}
117
118impl core::fmt::Debug for HSTRING {
119    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
120        write!(f, "{}", self.display())
121    }
122}
123
124impl From<&str> for HSTRING {
125    fn from(value: &str) -> Self {
126        unsafe { Self::from_wide_iter(value.encode_utf16(), value.len()) }
127    }
128}
129
130impl From<String> for HSTRING {
131    fn from(value: String) -> Self {
132        value.as_str().into()
133    }
134}
135
136impl From<&String> for HSTRING {
137    fn from(value: &String) -> Self {
138        value.as_str().into()
139    }
140}
141
142#[cfg(all(feature = "std", windows))]
143impl From<&std::path::Path> for HSTRING {
144    fn from(value: &std::path::Path) -> Self {
145        value.as_os_str().into()
146    }
147}
148
149#[cfg(all(feature = "std", windows))]
150impl From<&std::ffi::OsStr> for HSTRING {
151    fn from(value: &std::ffi::OsStr) -> Self {
152        unsafe {
153            Self::from_wide_iter(
154                std::os::windows::ffi::OsStrExt::encode_wide(value),
155                value.len(),
156            )
157        }
158    }
159}
160
161#[cfg(all(feature = "std", windows))]
162impl From<std::ffi::OsString> for HSTRING {
163    fn from(value: std::ffi::OsString) -> Self {
164        value.as_os_str().into()
165    }
166}
167
168#[cfg(all(feature = "std", windows))]
169impl From<&std::ffi::OsString> for HSTRING {
170    fn from(value: &std::ffi::OsString) -> Self {
171        value.as_os_str().into()
172    }
173}
174
175impl Eq for HSTRING {}
176
177impl Ord for HSTRING {
178    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
179        self.deref().cmp(other)
180    }
181}
182
183impl core::hash::Hash for HSTRING {
184    fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
185        self.deref().hash(hasher);
186    }
187}
188
189impl PartialOrd for HSTRING {
190    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
191        Some(self.cmp(other))
192    }
193}
194
195impl PartialEq for HSTRING {
196    fn eq(&self, other: &Self) -> bool {
197        self.deref() == other.deref()
198    }
199}
200
201impl PartialEq<String> for HSTRING {
202    fn eq(&self, other: &String) -> bool {
203        *self == **other
204    }
205}
206
207impl PartialEq<String> for &HSTRING {
208    fn eq(&self, other: &String) -> bool {
209        **self == **other
210    }
211}
212
213impl PartialEq<&String> for HSTRING {
214    fn eq(&self, other: &&String) -> bool {
215        *self == ***other
216    }
217}
218
219impl PartialEq<str> for HSTRING {
220    fn eq(&self, other: &str) -> bool {
221        self.iter().copied().eq(other.encode_utf16())
222    }
223}
224
225impl PartialEq<str> for &HSTRING {
226    fn eq(&self, other: &str) -> bool {
227        **self == *other
228    }
229}
230
231impl PartialEq<&str> for HSTRING {
232    fn eq(&self, other: &&str) -> bool {
233        *self == **other
234    }
235}
236
237impl PartialEq<HSTRING> for str {
238    fn eq(&self, other: &HSTRING) -> bool {
239        *other == *self
240    }
241}
242
243impl PartialEq<HSTRING> for &str {
244    fn eq(&self, other: &HSTRING) -> bool {
245        *other == **self
246    }
247}
248
249impl PartialEq<&HSTRING> for str {
250    fn eq(&self, other: &&HSTRING) -> bool {
251        **other == *self
252    }
253}
254
255impl PartialEq<HSTRING> for String {
256    fn eq(&self, other: &HSTRING) -> bool {
257        *other == **self
258    }
259}
260
261impl PartialEq<HSTRING> for &String {
262    fn eq(&self, other: &HSTRING) -> bool {
263        *other == ***self
264    }
265}
266
267impl PartialEq<&HSTRING> for String {
268    fn eq(&self, other: &&HSTRING) -> bool {
269        **other == **self
270    }
271}
272
273#[cfg(all(feature = "std", windows))]
274impl PartialEq<std::ffi::OsString> for HSTRING {
275    fn eq(&self, other: &std::ffi::OsString) -> bool {
276        *self == **other
277    }
278}
279
280#[cfg(all(feature = "std", windows))]
281impl PartialEq<std::ffi::OsString> for &HSTRING {
282    fn eq(&self, other: &std::ffi::OsString) -> bool {
283        **self == **other
284    }
285}
286
287#[cfg(all(feature = "std", windows))]
288impl PartialEq<&std::ffi::OsString> for HSTRING {
289    fn eq(&self, other: &&std::ffi::OsString) -> bool {
290        *self == ***other
291    }
292}
293
294#[cfg(all(feature = "std", windows))]
295impl PartialEq<std::ffi::OsStr> for HSTRING {
296    fn eq(&self, other: &std::ffi::OsStr) -> bool {
297        self.iter()
298            .copied()
299            .eq(std::os::windows::ffi::OsStrExt::encode_wide(other))
300    }
301}
302
303#[cfg(all(feature = "std", windows))]
304impl PartialEq<std::ffi::OsStr> for &HSTRING {
305    fn eq(&self, other: &std::ffi::OsStr) -> bool {
306        **self == *other
307    }
308}
309
310#[cfg(all(feature = "std", windows))]
311impl PartialEq<&std::ffi::OsStr> for HSTRING {
312    fn eq(&self, other: &&std::ffi::OsStr) -> bool {
313        *self == **other
314    }
315}
316
317#[cfg(all(feature = "std", windows))]
318impl PartialEq<HSTRING> for std::ffi::OsStr {
319    fn eq(&self, other: &HSTRING) -> bool {
320        *other == *self
321    }
322}
323
324#[cfg(all(feature = "std", windows))]
325impl PartialEq<HSTRING> for &std::ffi::OsStr {
326    fn eq(&self, other: &HSTRING) -> bool {
327        *other == **self
328    }
329}
330
331#[cfg(all(feature = "std", windows))]
332impl PartialEq<&HSTRING> for std::ffi::OsStr {
333    fn eq(&self, other: &&HSTRING) -> bool {
334        **other == *self
335    }
336}
337
338#[cfg(all(feature = "std", windows))]
339impl PartialEq<HSTRING> for std::ffi::OsString {
340    fn eq(&self, other: &HSTRING) -> bool {
341        *other == **self
342    }
343}
344
345#[cfg(all(feature = "std", windows))]
346impl PartialEq<HSTRING> for &std::ffi::OsString {
347    fn eq(&self, other: &HSTRING) -> bool {
348        *other == ***self
349    }
350}
351
352#[cfg(all(feature = "std", windows))]
353impl PartialEq<&HSTRING> for std::ffi::OsString {
354    fn eq(&self, other: &&HSTRING) -> bool {
355        **other == **self
356    }
357}
358
359impl TryFrom<&HSTRING> for String {
360    type Error = alloc::string::FromUtf16Error;
361
362    fn try_from(hstring: &HSTRING) -> Result<Self, Self::Error> {
363        Self::from_utf16(hstring)
364    }
365}
366
367impl TryFrom<HSTRING> for String {
368    type Error = alloc::string::FromUtf16Error;
369
370    fn try_from(hstring: HSTRING) -> Result<Self, Self::Error> {
371        Self::try_from(&hstring)
372    }
373}
374
375#[cfg(all(feature = "std", windows))]
376impl From<&HSTRING> for std::ffi::OsString {
377    fn from(hstring: &HSTRING) -> Self {
378        hstring.to_os_string()
379    }
380}
381
382#[cfg(all(feature = "std", windows))]
383impl From<HSTRING> for std::ffi::OsString {
384    fn from(hstring: HSTRING) -> Self {
385        Self::from(&hstring)
386    }
387}