Vendor dependencies for 0.3.0 release

This commit is contained in:
2025-09-27 10:29:08 -05:00
parent 0c8d39d483
commit 82ab7f317b
26803 changed files with 16134934 additions and 0 deletions

View File

@@ -0,0 +1,176 @@
use super::*;
/// A BSTR string ([BSTR](https://learn.microsoft.com/en-us/previous-versions/windows/desktop/automat/string-manipulation-functions))
/// is a length-prefixed wide string.
#[repr(transparent)]
pub struct BSTR(*const u16);
impl BSTR {
/// Create an empty `BSTR`.
///
/// This function does not allocate memory.
pub const fn new() -> Self {
Self(core::ptr::null_mut())
}
/// Returns `true` if the string is empty.
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Returns the length of the string.
pub fn len(&self) -> usize {
if self.0.is_null() {
0
} else {
unsafe { imp::SysStringLen(self.0) as usize }
}
}
/// Get the string as 16-bit wide characters (wchars).
pub fn as_wide(&self) -> &[u16] {
unsafe { core::slice::from_raw_parts(self.as_ptr(), self.len()) }
}
/// Returns a raw pointer to the `BSTR` buffer.
pub fn as_ptr(&self) -> *const u16 {
if !self.is_empty() {
self.0
} else {
const EMPTY: [u16; 1] = [0];
EMPTY.as_ptr()
}
}
/// Create a `BSTR` from a slice of 16 bit characters (wchars).
pub fn from_wide(value: &[u16]) -> Result<Self> {
if value.is_empty() {
return Ok(Self::new());
}
let result = unsafe {
Self(imp::SysAllocStringLen(
value.as_ptr(),
value.len().try_into()?,
))
};
if result.is_empty() {
Err(imp::E_OUTOFMEMORY.into())
} else {
Ok(result)
}
}
/// # Safety
#[doc(hidden)]
pub unsafe fn from_raw(raw: *const u16) -> Self {
Self(raw)
}
/// # Safety
#[doc(hidden)]
pub fn into_raw(self) -> *const u16 {
unsafe { core::mem::transmute(self) }
}
}
impl Clone for BSTR {
fn clone(&self) -> Self {
Self::from_wide(self.as_wide()).unwrap()
}
}
impl From<&str> for BSTR {
fn from(value: &str) -> Self {
let value: Vec<u16> = value.encode_utf16().collect();
Self::from_wide(&value).unwrap()
}
}
impl From<String> for BSTR {
fn from(value: String) -> Self {
value.as_str().into()
}
}
impl From<&String> for BSTR {
fn from(value: &String) -> Self {
value.as_str().into()
}
}
impl<'a> TryFrom<&'a BSTR> for String {
type Error = alloc::string::FromUtf16Error;
fn try_from(value: &BSTR) -> core::result::Result<Self, Self::Error> {
String::from_utf16(value.as_wide())
}
}
impl TryFrom<BSTR> for String {
type Error = alloc::string::FromUtf16Error;
fn try_from(value: BSTR) -> core::result::Result<Self, Self::Error> {
String::try_from(&value)
}
}
impl Default for BSTR {
fn default() -> Self {
Self(core::ptr::null_mut())
}
}
impl core::fmt::Display for BSTR {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
core::write!(
f,
"{}",
Decode(|| core::char::decode_utf16(self.as_wide().iter().cloned()))
)
}
}
impl core::fmt::Debug for BSTR {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
core::write!(f, "{}", self)
}
}
impl PartialEq for BSTR {
fn eq(&self, other: &Self) -> bool {
self.as_wide() == other.as_wide()
}
}
impl Eq for BSTR {}
impl PartialEq<BSTR> for &str {
fn eq(&self, other: &BSTR) -> bool {
other == self
}
}
impl PartialEq<BSTR> for String {
fn eq(&self, other: &BSTR) -> bool {
other == self
}
}
impl<T: AsRef<str> + ?Sized> PartialEq<T> for BSTR {
fn eq(&self, other: &T) -> bool {
self.as_wide()
.iter()
.copied()
.eq(other.as_ref().encode_utf16())
}
}
impl Drop for BSTR {
fn drop(&mut self) {
if !self.0.is_null() {
unsafe { imp::SysFreeString(self.0) }
}
}
}

View File

@@ -0,0 +1,459 @@
use super::*;
/// A WinRT string ([HSTRING](https://docs.microsoft.com/en-us/windows/win32/winrt/hstring))
/// is reference-counted and immutable.
#[repr(transparent)]
pub struct HSTRING(Option<core::ptr::NonNull<Header>>);
impl HSTRING {
/// Create an empty `HSTRING`.
///
/// This function does not allocate memory.
pub const fn new() -> Self {
Self(None)
}
/// Returns `true` if the string is empty.
pub const fn is_empty(&self) -> bool {
// An empty HSTRING is represented by a null pointer.
self.0.is_none()
}
/// Returns the length of the string. The length is measured in `u16`s (UTF-16 code units), not including the terminating null character.
pub fn len(&self) -> usize {
if let Some(header) = self.get_header() {
header.len as usize
} else {
0
}
}
/// Get the string as 16-bit wide characters (wchars).
pub fn as_wide(&self) -> &[u16] {
unsafe { core::slice::from_raw_parts(self.as_ptr(), self.len()) }
}
/// Returns a raw pointer to the `HSTRING` buffer.
pub fn as_ptr(&self) -> *const u16 {
if let Some(header) = self.get_header() {
header.data
} else {
const EMPTY: [u16; 1] = [0];
EMPTY.as_ptr()
}
}
/// Create a `HSTRING` from a slice of 16 bit characters (wchars).
pub fn from_wide(value: &[u16]) -> Result<Self> {
unsafe { Self::from_wide_iter(value.iter().copied(), value.len()) }
}
/// Get the contents of this `HSTRING` as a String lossily.
pub fn to_string_lossy(&self) -> String {
String::from_utf16_lossy(self.as_wide())
}
/// Get the contents of this `HSTRING` as a OsString.
#[cfg(all(feature = "std", windows))]
pub fn to_os_string(&self) -> std::ffi::OsString {
std::os::windows::ffi::OsStringExt::from_wide(self.as_wide())
}
/// # Safety
/// len must not be less than the number of items in the iterator.
unsafe fn from_wide_iter<I: Iterator<Item = u16>>(iter: I, len: usize) -> Result<Self> {
if len == 0 {
return Ok(Self::new());
}
let ptr = Header::alloc(len.try_into()?)?;
// Place each utf-16 character into the buffer and
// increase len as we go along.
for (index, wide) in iter.enumerate() {
debug_assert!(index < len);
core::ptr::write((*ptr).data.add(index), wide);
(*ptr).len = index as u32 + 1;
}
// Write a 0 byte to the end of the buffer.
core::ptr::write((*ptr).data.offset((*ptr).len as isize), 0);
Ok(Self(core::ptr::NonNull::new(ptr)))
}
fn get_header(&self) -> Option<&Header> {
self.0.map(|header| unsafe { header.as_ref() })
}
}
impl Default for HSTRING {
fn default() -> Self {
Self::new()
}
}
impl Clone for HSTRING {
fn clone(&self) -> Self {
if let Some(header) = self.get_header() {
Self(core::ptr::NonNull::new(header.duplicate().unwrap()))
} else {
Self::new()
}
}
}
impl Drop for HSTRING {
fn drop(&mut self) {
if self.is_empty() {
return;
}
if let Some(header) = self.0.take() {
// REFERENCE_FLAG indicates a string backed by static or stack memory that is
// thus not reference-counted and does not need to be freed.
unsafe {
let header = header.as_ref();
if header.flags & REFERENCE_FLAG == 0 && header.count.release() == 0 {
imp::heap_free(header as *const _ as *mut _);
}
}
}
}
}
unsafe impl Send for HSTRING {}
unsafe impl Sync for HSTRING {}
impl core::fmt::Display for HSTRING {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(
f,
"{}",
Decode(|| core::char::decode_utf16(self.as_wide().iter().cloned()))
)
}
}
impl core::fmt::Debug for HSTRING {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "\"{}\"", self)
}
}
impl From<&str> for HSTRING {
fn from(value: &str) -> Self {
unsafe { Self::from_wide_iter(value.encode_utf16(), value.len()).unwrap() }
}
}
impl From<String> for HSTRING {
fn from(value: String) -> Self {
value.as_str().into()
}
}
impl From<&String> for HSTRING {
fn from(value: &String) -> Self {
value.as_str().into()
}
}
#[cfg(all(feature = "std", windows))]
impl From<&std::path::Path> for HSTRING {
fn from(value: &std::path::Path) -> Self {
value.as_os_str().into()
}
}
#[cfg(all(feature = "std", windows))]
impl From<&std::ffi::OsStr> for HSTRING {
fn from(value: &std::ffi::OsStr) -> Self {
unsafe {
Self::from_wide_iter(
std::os::windows::ffi::OsStrExt::encode_wide(value),
value.len(),
)
.unwrap()
}
}
}
#[cfg(all(feature = "std", windows))]
impl From<std::ffi::OsString> for HSTRING {
fn from(value: std::ffi::OsString) -> Self {
value.as_os_str().into()
}
}
#[cfg(all(feature = "std", windows))]
impl From<&std::ffi::OsString> for HSTRING {
fn from(value: &std::ffi::OsString) -> Self {
value.as_os_str().into()
}
}
impl Eq for HSTRING {}
impl Ord for HSTRING {
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
self.as_wide().cmp(other.as_wide())
}
}
impl core::hash::Hash for HSTRING {
fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
self.as_wide().hash(hasher)
}
}
impl PartialOrd for HSTRING {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for HSTRING {
fn eq(&self, other: &Self) -> bool {
*self.as_wide() == *other.as_wide()
}
}
impl PartialEq<String> for HSTRING {
fn eq(&self, other: &String) -> bool {
*self == **other
}
}
impl PartialEq<String> for &HSTRING {
fn eq(&self, other: &String) -> bool {
**self == **other
}
}
impl PartialEq<&String> for HSTRING {
fn eq(&self, other: &&String) -> bool {
*self == ***other
}
}
impl PartialEq<str> for HSTRING {
fn eq(&self, other: &str) -> bool {
self.as_wide().iter().copied().eq(other.encode_utf16())
}
}
impl PartialEq<str> for &HSTRING {
fn eq(&self, other: &str) -> bool {
**self == *other
}
}
impl PartialEq<&str> for HSTRING {
fn eq(&self, other: &&str) -> bool {
*self == **other
}
}
impl PartialEq<HSTRING> for str {
fn eq(&self, other: &HSTRING) -> bool {
*other == *self
}
}
impl PartialEq<HSTRING> for &str {
fn eq(&self, other: &HSTRING) -> bool {
*other == **self
}
}
impl PartialEq<&HSTRING> for str {
fn eq(&self, other: &&HSTRING) -> bool {
**other == *self
}
}
impl PartialEq<HSTRING> for String {
fn eq(&self, other: &HSTRING) -> bool {
*other == **self
}
}
impl PartialEq<HSTRING> for &String {
fn eq(&self, other: &HSTRING) -> bool {
*other == ***self
}
}
impl PartialEq<&HSTRING> for String {
fn eq(&self, other: &&HSTRING) -> bool {
**other == **self
}
}
#[cfg(all(feature = "std", windows))]
impl PartialEq<std::ffi::OsString> for HSTRING {
fn eq(&self, other: &std::ffi::OsString) -> bool {
*self == **other
}
}
#[cfg(all(feature = "std", windows))]
impl PartialEq<std::ffi::OsString> for &HSTRING {
fn eq(&self, other: &std::ffi::OsString) -> bool {
**self == **other
}
}
#[cfg(all(feature = "std", windows))]
impl PartialEq<&std::ffi::OsString> for HSTRING {
fn eq(&self, other: &&std::ffi::OsString) -> bool {
*self == ***other
}
}
#[cfg(all(feature = "std", windows))]
impl PartialEq<std::ffi::OsStr> for HSTRING {
fn eq(&self, other: &std::ffi::OsStr) -> bool {
self.as_wide()
.iter()
.copied()
.eq(std::os::windows::ffi::OsStrExt::encode_wide(other))
}
}
#[cfg(all(feature = "std", windows))]
impl PartialEq<std::ffi::OsStr> for &HSTRING {
fn eq(&self, other: &std::ffi::OsStr) -> bool {
**self == *other
}
}
#[cfg(all(feature = "std", windows))]
impl PartialEq<&std::ffi::OsStr> for HSTRING {
fn eq(&self, other: &&std::ffi::OsStr) -> bool {
*self == **other
}
}
#[cfg(all(feature = "std", windows))]
impl PartialEq<HSTRING> for std::ffi::OsStr {
fn eq(&self, other: &HSTRING) -> bool {
*other == *self
}
}
#[cfg(all(feature = "std", windows))]
impl PartialEq<HSTRING> for &std::ffi::OsStr {
fn eq(&self, other: &HSTRING) -> bool {
*other == **self
}
}
#[cfg(all(feature = "std", windows))]
impl PartialEq<&HSTRING> for std::ffi::OsStr {
fn eq(&self, other: &&HSTRING) -> bool {
**other == *self
}
}
#[cfg(all(feature = "std", windows))]
impl PartialEq<HSTRING> for std::ffi::OsString {
fn eq(&self, other: &HSTRING) -> bool {
*other == **self
}
}
#[cfg(all(feature = "std", windows))]
impl PartialEq<HSTRING> for &std::ffi::OsString {
fn eq(&self, other: &HSTRING) -> bool {
*other == ***self
}
}
#[cfg(all(feature = "std", windows))]
impl PartialEq<&HSTRING> for std::ffi::OsString {
fn eq(&self, other: &&HSTRING) -> bool {
**other == **self
}
}
impl<'a> TryFrom<&'a HSTRING> for String {
type Error = alloc::string::FromUtf16Error;
fn try_from(hstring: &HSTRING) -> core::result::Result<Self, Self::Error> {
String::from_utf16(hstring.as_wide())
}
}
impl TryFrom<HSTRING> for String {
type Error = alloc::string::FromUtf16Error;
fn try_from(hstring: HSTRING) -> core::result::Result<Self, Self::Error> {
String::try_from(&hstring)
}
}
#[cfg(all(feature = "std", windows))]
impl<'a> From<&'a HSTRING> for std::ffi::OsString {
fn from(hstring: &HSTRING) -> Self {
hstring.to_os_string()
}
}
#[cfg(all(feature = "std", windows))]
impl From<HSTRING> for std::ffi::OsString {
fn from(hstring: HSTRING) -> Self {
Self::from(&hstring)
}
}
const REFERENCE_FLAG: u32 = 1;
#[repr(C)]
struct Header {
flags: u32,
len: u32,
_0: u32,
_1: u32,
data: *mut u16,
count: imp::RefCount,
buffer_start: u16,
}
impl Header {
fn alloc(len: u32) -> Result<*mut Header> {
debug_assert!(len != 0);
// Allocate enough space for header and two bytes per character.
// The space for the terminating null character is already accounted for inside of `Header`.
let alloc_size = core::mem::size_of::<Header>() + 2 * len as usize;
let header = imp::heap_alloc(alloc_size)? as *mut Header;
// SAFETY: uses `core::ptr::write` (since `header` is unintialized). `Header` is safe to be all zeros.
unsafe {
header.write(core::mem::MaybeUninit::<Header>::zeroed().assume_init());
(*header).len = len;
(*header).count = imp::RefCount::new(1);
(*header).data = &mut (*header).buffer_start;
}
Ok(header)
}
fn duplicate(&self) -> Result<*mut Header> {
if self.flags & REFERENCE_FLAG == 0 {
// If this is not a "fast pass" string then simply increment the reference count.
self.count.add_ref();
Ok(self as *const Header as *mut Header)
} else {
// Otherwise, allocate a new string and copy the value into the new string.
let copy = Header::alloc(self.len)?;
// SAFETY: since we are duplicating the string it is safe to copy all data from self to the initialized `copy`.
// We copy `len + 1` characters since `len` does not account for the terminating null character.
unsafe {
core::ptr::copy_nonoverlapping(self.data, (*copy).data, self.len as usize + 1);
}
Ok(copy)
}
}
}

View File

@@ -0,0 +1,167 @@
/// A literal UTF-8 string with a trailing null terminator.
#[macro_export]
macro_rules! s {
($s:literal) => {
$crate::PCSTR::from_raw(::core::concat!($s, '\0').as_ptr())
};
}
/// A literal UTF-16 wide string with a trailing null terminator.
#[macro_export]
macro_rules! w {
($s:literal) => {{
const INPUT: &[u8] = $s.as_bytes();
const OUTPUT_LEN: usize = $crate::utf16_len(INPUT) + 1;
const OUTPUT: &[u16; OUTPUT_LEN] = {
let mut buffer = [0; OUTPUT_LEN];
let mut input_pos = 0;
let mut output_pos = 0;
while let Some((mut code_point, new_pos)) = $crate::decode_utf8_char(INPUT, input_pos) {
input_pos = new_pos;
if code_point <= 0xffff {
buffer[output_pos] = code_point as u16;
output_pos += 1;
} else {
code_point -= 0x10000;
buffer[output_pos] = 0xd800 + (code_point >> 10) as u16;
output_pos += 1;
buffer[output_pos] = 0xdc00 + (code_point & 0x3ff) as u16;
output_pos += 1;
}
}
&{ buffer }
};
$crate::PCWSTR::from_raw(OUTPUT.as_ptr())
}};
}
/// A literal HSTRING, length-prefixed wide string with a trailing null terminator.
#[macro_export]
macro_rules! h {
($s:literal) => {{
const INPUT: &[u8] = $s.as_bytes();
const OUTPUT_LEN: usize = $crate::utf16_len(INPUT) + 1;
#[allow(clippy::declare_interior_mutable_const)]
const RESULT: $crate::HSTRING = {
if OUTPUT_LEN == 1 {
unsafe { ::std::mem::transmute(::std::ptr::null::<u16>()) }
} else {
const OUTPUT: $crate::PCWSTR = $crate::w!($s);
const HEADER: $crate::HSTRING_HEADER = $crate::HSTRING_HEADER {
flags: 0x11,
len: (OUTPUT_LEN - 1) as u32,
padding1: 0,
padding2: 0,
ptr: OUTPUT.as_ptr(),
};
// SAFETY: an `HSTRING` is exactly equivalent to a pointer to an `HSTRING_HEADER`
unsafe {
::std::mem::transmute::<&$crate::HSTRING_HEADER, $crate::HSTRING>(&HEADER)
}
}
};
#[allow(clippy::borrow_interior_mutable_const)]
&RESULT
}};
}
#[doc(hidden)]
pub const fn decode_utf8_char(bytes: &[u8], mut pos: usize) -> Option<(u32, usize)> {
if bytes.len() == pos {
return None;
}
let ch = bytes[pos] as u32;
pos += 1;
if ch <= 0x7f {
return Some((ch, pos));
}
if (ch & 0xe0) == 0xc0 {
if bytes.len() - pos < 1 {
return None;
}
let ch2 = bytes[pos] as u32;
pos += 1;
if (ch2 & 0xc0) != 0x80 {
return None;
}
let result: u32 = ((ch & 0x1f) << 6) | (ch2 & 0x3f);
if result <= 0x7f {
return None;
}
return Some((result, pos));
}
if (ch & 0xf0) == 0xe0 {
if bytes.len() - pos < 2 {
return None;
}
let ch2 = bytes[pos] as u32;
pos += 1;
let ch3 = bytes[pos] as u32;
pos += 1;
if (ch2 & 0xc0) != 0x80 || (ch3 & 0xc0) != 0x80 {
return None;
}
let result = ((ch & 0x0f) << 12) | ((ch2 & 0x3f) << 6) | (ch3 & 0x3f);
if result <= 0x7ff || (0xd800 <= result && result <= 0xdfff) {
return None;
}
return Some((result, pos));
}
if (ch & 0xf8) == 0xf0 {
if bytes.len() - pos < 3 {
return None;
}
let ch2 = bytes[pos] as u32;
pos += 1;
let ch3 = bytes[pos] as u32;
pos += 1;
let ch4 = bytes[pos] as u32;
pos += 1;
if (ch2 & 0xc0) != 0x80 || (ch3 & 0xc0) != 0x80 || (ch4 & 0xc0) != 0x80 {
return None;
}
let result =
((ch & 0x07) << 18) | ((ch2 & 0x3f) << 12) | ((ch3 & 0x3f) << 6) | (ch4 & 0x3f);
if result <= 0xffff || 0x10ffff < result {
return None;
}
return Some((result, pos));
}
None
}
#[doc(hidden)]
#[repr(C)]
pub struct HSTRING_HEADER {
pub flags: u32,
pub len: u32,
pub padding1: u32,
pub padding2: u32,
pub ptr: *const u16,
}
#[doc(hidden)]
pub const fn utf16_len(bytes: &[u8]) -> usize {
let mut pos = 0;
let mut len = 0;
while let Some((code_point, new_pos)) = decode_utf8_char(bytes, pos) {
pos = new_pos;
len += if code_point <= 0xffff { 1 } else { 2 };
}
len
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test() {
assert_eq!(decode_utf8_char(b"123", 0), Some((0x31, 1)));
assert_eq!(decode_utf8_char(b"123", 1), Some((0x32, 2)));
assert_eq!(decode_utf8_char(b"123", 2), Some((0x33, 3)));
assert_eq!(decode_utf8_char(b"123", 3), None);
assert_eq!(utf16_len(b"123"), 3);
assert_eq!(utf16_len("α & ω".as_bytes()), 5);
}
}

View File

@@ -0,0 +1,82 @@
mod bstr;
mod hstring;
mod literals;
mod pcstr;
mod pcwstr;
mod pstr;
mod pwstr;
pub use bstr::*;
pub use hstring::*;
#[doc(hidden)]
pub use literals::*;
pub use pcstr::*;
pub use pcwstr::*;
pub use pstr::*;
pub use pwstr::*;
use super::*;
extern "C" {
#[doc(hidden)]
pub fn strlen(s: PCSTR) -> usize;
}
/// An internal helper for decoding an iterator of chars and displaying them
struct Decode<F>(pub F);
impl<F, R, E> core::fmt::Display for Decode<F>
where
F: Clone + FnOnce() -> R,
R: IntoIterator<Item = core::result::Result<char, E>>,
{
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
use core::fmt::Write;
let iter = self.0.clone();
for c in iter().into_iter() {
f.write_char(c.unwrap_or(core::char::REPLACEMENT_CHARACTER))?
}
Ok(())
}
}
/// Mirror of `std::char::decode_utf16` for utf-8.
fn decode_utf8(
mut buffer: &[u8],
) -> impl Iterator<Item = core::result::Result<char, core::str::Utf8Error>> + '_ {
let mut current = "".chars();
let mut previous_error = None;
core::iter::from_fn(move || {
loop {
match (current.next(), previous_error) {
(Some(c), _) => return Some(Ok(c)),
// Return the previous error
(None, Some(e)) => {
previous_error = None;
return Some(Err(e));
}
// We're completely done
(None, None) if buffer.is_empty() => return None,
(None, None) => {
match core::str::from_utf8(buffer) {
Ok(s) => {
current = s.chars();
buffer = &[];
}
Err(e) => {
let (valid, rest) = buffer.split_at(e.valid_up_to());
// Skip the invalid sequence and stop completely if we ended early
let invalid_sequence_length = e.error_len()?;
buffer = &rest[invalid_sequence_length..];
// Set the current iterator to the valid section and indicate previous error
// SAFETY: `valid` is known to be valid utf-8 from error
current = unsafe { core::str::from_utf8_unchecked(valid) }.chars();
previous_error = Some(e);
}
}
}
}
}
})
}

View File

@@ -0,0 +1,56 @@
use super::*;
/// A pointer to a constant null-terminated string of 8-bit Windows (ANSI) characters.
#[repr(transparent)]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct PCSTR(pub *const u8);
impl PCSTR {
/// Construct a new `PCSTR` from a raw pointer
pub const fn from_raw(ptr: *const u8) -> Self {
Self(ptr)
}
/// Construct a null `PCSTR`
pub const fn null() -> Self {
Self(core::ptr::null())
}
/// Returns a raw pointer to the `PCSTR`
pub const fn as_ptr(&self) -> *const u8 {
self.0
}
/// Checks whether the `PCSTR` is null
pub fn is_null(&self) -> bool {
self.0.is_null()
}
/// String data without the trailing 0
///
/// # Safety
///
/// The `PCSTR`'s pointer needs to be valid for reads up until and including the next `\0`.
pub unsafe fn as_bytes(&self) -> &[u8] {
let len = strlen(*self);
core::slice::from_raw_parts(self.0, len)
}
/// Copy the `PCSTR` into a Rust `String`.
///
/// # Safety
///
/// See the safety information for `PCSTR::as_bytes`.
pub unsafe fn to_string(&self) -> core::result::Result<String, alloc::string::FromUtf8Error> {
String::from_utf8(self.as_bytes().into())
}
/// Allow this string to be displayed.
///
/// # Safety
///
/// See the safety information for `PCSTR::as_bytes`.
pub unsafe fn display(&self) -> impl core::fmt::Display + '_ {
Decode(move || decode_utf8(self.as_bytes()))
}
}

View File

@@ -0,0 +1,101 @@
use super::*;
/// A pointer to a constant null-terminated string of 16-bit Unicode characters.
#[repr(transparent)]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct PCWSTR(pub *const u16);
impl PCWSTR {
/// Construct a new `PCWSTR` from a raw pointer
pub const fn from_raw(ptr: *const u16) -> Self {
Self(ptr)
}
/// Construct a null `PCWSTR`
pub const fn null() -> Self {
Self(core::ptr::null())
}
/// Returns a raw pointer to the `PCWSTR`
pub const fn as_ptr(&self) -> *const u16 {
self.0
}
/// Checks whether the `PCWSTR` is null
pub fn is_null(&self) -> bool {
self.0.is_null()
}
/// String length without the trailing 0
///
/// # Safety
///
/// The `PCWSTR`'s pointer needs to be valid for reads up until and including the next `\0`.
pub unsafe fn len(&self) -> usize {
#[cfg(windows)]
let len = {
extern "C" {
fn wcslen(s: *const u16) -> usize;
}
wcslen(self.0)
};
#[cfg(not(windows))]
let len = {
let mut len = 0;
let mut ptr = self.0;
while ptr.read() != 0 {
len += 1;
ptr = ptr.add(1);
}
len
};
len
}
/// Returns `true` if the string length is zero, and `false` otherwise.
///
/// # Safety
///
/// The `PCWSTR`'s pointer needs to be valid for reads up until and including the next `\0`.
pub unsafe fn is_empty(&self) -> bool {
self.len() == 0
}
/// String data without the trailing 0
///
/// # Safety
///
/// The `PCWSTR`'s pointer needs to be valid for reads up until and including the next `\0`.
pub unsafe fn as_wide(&self) -> &[u16] {
core::slice::from_raw_parts(self.0, self.len())
}
/// Copy the `PCWSTR` into a Rust `String`.
///
/// # Safety
///
/// See the safety information for `PCWSTR::as_wide`.
pub unsafe fn to_string(&self) -> core::result::Result<String, alloc::string::FromUtf16Error> {
String::from_utf16(self.as_wide())
}
/// Copy the `PCWSTR` into an `HSTRING`.
///
/// # Safety
///
/// See the safety information for `PCWSTR::as_wide`.
pub unsafe fn to_hstring(&self) -> Result<HSTRING> {
HSTRING::from_wide(self.as_wide())
}
/// Allow this string to be displayed.
///
/// # Safety
///
/// See the safety information for `PCWSTR::as_wide`.
pub unsafe fn display(&self) -> impl core::fmt::Display + '_ {
Decode(move || core::char::decode_utf16(self.as_wide().iter().cloned()))
}
}

View File

@@ -0,0 +1,56 @@
use super::*;
/// A pointer to a null-terminated string of 8-bit Windows (ANSI) characters.
#[repr(transparent)]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct PSTR(pub *mut u8);
impl PSTR {
/// Construct a new `PSTR` from a raw pointer
pub const fn from_raw(ptr: *mut u8) -> Self {
Self(ptr)
}
/// Construct a null `PSTR`
pub const fn null() -> Self {
Self(core::ptr::null_mut())
}
/// Returns a raw pointer to the `PSTR`
pub const fn as_ptr(&self) -> *mut u8 {
self.0
}
/// Checks whether the `PSTR` is null
pub fn is_null(&self) -> bool {
self.0.is_null()
}
/// String data without the trailing 0
///
/// # Safety
///
/// The `PSTR`'s pointer needs to be valid for reads up until and including the next `\0`.
pub unsafe fn as_bytes(&self) -> &[u8] {
let len = strlen(PCSTR::from_raw(self.0));
core::slice::from_raw_parts(self.0, len)
}
/// Copy the `PSTR` into a Rust `String`.
///
/// # Safety
///
/// See the safety information for `PSTR::as_bytes`.
pub unsafe fn to_string(&self) -> core::result::Result<String, alloc::string::FromUtf8Error> {
String::from_utf8(self.as_bytes().into())
}
/// Allow this string to be displayed.
///
/// # Safety
///
/// See the safety information for `PSTR::as_bytes`.
pub unsafe fn display(&self) -> impl core::fmt::Display + '_ {
Decode(move || decode_utf8(self.as_bytes()))
}
}

View File

@@ -0,0 +1,82 @@
use super::*;
/// A pointer to a null-terminated string of 16-bit Unicode characters.
#[repr(transparent)]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct PWSTR(pub *mut u16);
impl PWSTR {
/// Construct a new `PWSTR` from a raw pointer.
pub const fn from_raw(ptr: *mut u16) -> Self {
Self(ptr)
}
/// Construct a null `PWSTR`.
pub const fn null() -> Self {
Self(core::ptr::null_mut())
}
/// Returns a raw pointer to the `PWSTR`.
pub const fn as_ptr(&self) -> *mut u16 {
self.0
}
/// Checks whether the `PWSTR` is null.
pub fn is_null(&self) -> bool {
self.0.is_null()
}
/// String length without the trailing 0
///
/// # Safety
///
/// The `PWSTR`'s pointer needs to be valid for reads up until and including the next `\0`.
pub unsafe fn len(&self) -> usize {
PCWSTR(self.0).len()
}
/// Returns `true` if the string length is zero, and `false` otherwise.
///
/// # Safety
///
/// The `PWSTR`'s pointer needs to be valid for reads up until and including the next `\0`.
pub unsafe fn is_empty(&self) -> bool {
self.len() == 0
}
/// String data without the trailing 0.
///
/// # Safety
///
/// The `PWSTR`'s pointer needs to be valid for reads up until and including the next `\0`.
pub unsafe fn as_wide(&self) -> &[u16] {
core::slice::from_raw_parts(self.0, self.len())
}
/// Copy the `PWSTR` into a Rust `String`.
///
/// # Safety
///
/// See the safety information for `PWSTR::as_wide`.
pub unsafe fn to_string(&self) -> core::result::Result<String, alloc::string::FromUtf16Error> {
String::from_utf16(self.as_wide())
}
/// Copy the `PWSTR` into an `HSTRING`.
///
/// # Safety
///
/// See the safety information for `PWSTR::as_wide`.
pub unsafe fn to_hstring(&self) -> Result<HSTRING> {
HSTRING::from_wide(self.as_wide())
}
/// Allow this string to be displayed.
///
/// # Safety
///
/// See the safety information for `PWSTR::as_wide`.
pub unsafe fn display(&self) -> impl core::fmt::Display + '_ {
Decode(move || core::char::decode_utf16(self.as_wide().iter().cloned()))
}
}