Skip to main content

windows_strings/
pcwstr.rs

1use super::*;
2
3/// A pointer to a constant null-terminated string of 16-bit Unicode characters.
4#[repr(transparent)]
5#[derive(Clone, Copy, PartialEq, Eq, Debug)]
6pub struct PCWSTR(pub *const u16);
7
8impl PCWSTR {
9    /// Constructs a `PCWSTR` from a raw pointer.
10    pub const fn from_raw(ptr: *const u16) -> Self {
11        Self(ptr)
12    }
13
14    /// Constructs a null `PCWSTR`.
15    pub const fn null() -> Self {
16        Self(core::ptr::null())
17    }
18
19    /// Returns the raw pointer.
20    pub const fn as_ptr(&self) -> *const u16 {
21        self.0
22    }
23
24    /// Returns whether the pointer is null.
25    pub fn is_null(&self) -> bool {
26        self.0.is_null()
27    }
28
29    /// Returns the string length without the trailing null.
30    ///
31    /// # Safety
32    ///
33    /// The `PCWSTR`'s pointer needs to be valid for reads up until and including the next `\0`.
34    pub unsafe fn len(&self) -> usize {
35        unsafe extern "C" {
36            fn wcslen(s: *const u16) -> usize;
37        }
38        unsafe { wcslen(self.0) }
39    }
40
41    /// Returns whether the string is empty.
42    ///
43    /// # Safety
44    ///
45    /// The `PCWSTR`'s pointer needs to be valid for reads up until and including the next `\0`.
46    pub unsafe fn is_empty(&self) -> bool {
47        unsafe { self.len() == 0 }
48    }
49
50    /// Returns the string data without the trailing null.
51    ///
52    /// # Safety
53    ///
54    /// The `PCWSTR`'s pointer needs to be valid for reads up until and including the next `\0`.
55    pub unsafe fn as_wide(&self) -> &[u16] {
56        unsafe { core::slice::from_raw_parts(self.0, self.len()) }
57    }
58
59    /// Copies the string into a Rust `String`.
60    ///
61    /// # Safety
62    ///
63    /// See the safety information for `PCWSTR::as_wide`.
64    pub unsafe fn to_string(&self) -> Result<String, alloc::string::FromUtf16Error> {
65        unsafe { String::from_utf16(self.as_wide()) }
66    }
67
68    /// Copies the string into an `HSTRING`.
69    ///
70    /// # Safety
71    ///
72    /// See the safety information for `PCWSTR::as_wide`.
73    pub unsafe fn to_hstring(&self) -> HSTRING {
74        unsafe { HSTRING::from_wide(self.as_wide()) }
75    }
76
77    /// Returns a display adapter for the string.
78    ///
79    /// # Safety
80    ///
81    /// See the safety information for `PCWSTR::as_wide`.
82    pub unsafe fn display(&self) -> impl core::fmt::Display + '_ {
83        unsafe { Decode(move || core::char::decode_utf16(self.as_wide().iter().copied())) }
84    }
85}
86
87impl Default for PCWSTR {
88    fn default() -> Self {
89        Self::null()
90    }
91}
92
93impl AsRef<Self> for PCWSTR {
94    fn as_ref(&self) -> &Self {
95        self
96    }
97}
98
99impl core::ops::Deref for PCWSTR {
100    type Target = *const u16;
101
102    fn deref(&self) -> &Self::Target {
103        &self.0
104    }
105}