Skip to main content

windows_strings/
pstr.rs

1use super::*;
2
3/// A pointer to a null-terminated string of 8-bit Windows (ANSI) characters.
4#[repr(transparent)]
5#[derive(Clone, Copy, PartialEq, Eq, Debug)]
6pub struct PSTR(pub *mut u8);
7
8impl PSTR {
9    /// Constructs a `PSTR` from a raw pointer.
10    pub const fn from_raw(ptr: *mut u8) -> Self {
11        Self(ptr)
12    }
13
14    /// Constructs a null `PSTR`.
15    pub const fn null() -> Self {
16        Self(core::ptr::null_mut())
17    }
18
19    /// Returns the raw pointer.
20    pub const fn as_ptr(&self) -> *mut u8 {
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 data without the trailing null.
30    ///
31    /// # Safety
32    ///
33    /// The `PSTR`'s pointer needs to be valid for reads up until and including the next `\0`.
34    pub unsafe fn as_bytes(&self) -> &[u8] {
35        unsafe {
36            let len = strlen(self.0.cast());
37            core::slice::from_raw_parts(self.0, len)
38        }
39    }
40
41    /// Copies the string into a Rust `String`.
42    ///
43    /// # Safety
44    ///
45    /// See the safety information for `PSTR::as_bytes`.
46    pub unsafe fn to_string(&self) -> Result<String, alloc::string::FromUtf8Error> {
47        unsafe { String::from_utf8(self.as_bytes().into()) }
48    }
49
50    /// Returns a display adapter for the string.
51    ///
52    /// # Safety
53    ///
54    /// See the safety information for `PSTR::as_bytes`.
55    pub unsafe fn display(&self) -> impl core::fmt::Display + '_ {
56        unsafe { Decode(move || decode_utf8(self.as_bytes())) }
57    }
58}
59
60impl Default for PSTR {
61    fn default() -> Self {
62        Self::null()
63    }
64}