windows_strings/
pwstr.rs

1use super::*;
2
3/// A pointer to a null-terminated string of 16-bit Unicode characters.
4#[repr(transparent)]
5#[derive(Clone, Copy, PartialEq, Eq, Debug)]
6pub struct PWSTR(pub *mut u16);
7
8impl PWSTR {
9    /// Construct a new `PWSTR` from a raw pointer.
10    pub const fn from_raw(ptr: *mut u16) -> Self {
11        Self(ptr)
12    }
13
14    /// Construct a null `PWSTR`.
15    pub const fn null() -> Self {
16        Self(core::ptr::null_mut())
17    }
18
19    /// Returns a raw pointer to the `PWSTR`.
20    pub const fn as_ptr(&self) -> *mut u16 {
21        self.0
22    }
23
24    /// Checks whether the `PWSTR` is null.
25    pub fn is_null(&self) -> bool {
26        self.0.is_null()
27    }
28
29    /// String length without the trailing 0
30    ///
31    /// # Safety
32    ///
33    /// The `PWSTR`'s pointer needs to be valid for reads up until and including the next `\0`.
34    pub unsafe fn len(&self) -> usize {
35        unsafe { PCWSTR(self.0).len() }
36    }
37
38    /// Returns `true` if the string length is zero, and `false` otherwise.
39    ///
40    /// # Safety
41    ///
42    /// The `PWSTR`'s pointer needs to be valid for reads up until and including the next `\0`.
43    pub unsafe fn is_empty(&self) -> bool {
44        unsafe { self.len() == 0 }
45    }
46
47    /// String data without the trailing 0.
48    ///
49    /// # Safety
50    ///
51    /// The `PWSTR`'s pointer needs to be valid for reads up until and including the next `\0`.
52    pub unsafe fn as_wide(&self) -> &[u16] {
53        unsafe { core::slice::from_raw_parts(self.0, self.len()) }
54    }
55
56    /// Copy the `PWSTR` into a Rust `String`.
57    ///
58    /// # Safety
59    ///
60    /// See the safety information for `PWSTR::as_wide`.
61    pub unsafe fn to_string(&self) -> core::result::Result<String, alloc::string::FromUtf16Error> {
62        unsafe { String::from_utf16(self.as_wide()) }
63    }
64
65    /// Copy the `PWSTR` into an `HSTRING`.
66    ///
67    /// # Safety
68    ///
69    /// See the safety information for `PWSTR::as_wide`.
70    pub unsafe fn to_hstring(&self) -> HSTRING {
71        unsafe { HSTRING::from_wide(self.as_wide()) }
72    }
73
74    /// Allow this string to be displayed.
75    ///
76    /// # Safety
77    ///
78    /// See the safety information for `PWSTR::as_wide`.
79    pub unsafe fn display(&self) -> impl core::fmt::Display + '_ {
80        unsafe { Decode(move || core::char::decode_utf16(self.as_wide().iter().cloned())) }
81    }
82}