Skip to main content

stable_osstring_encoding/
stable_os_string.rs

1use crate::{EncodingWidth, FromRawStableEncoding};
2#[cfg(doc)]
3use std::ffi::OsStr;
4use std::{ffi::OsString, fmt, hash::Hash, ops::Deref, path::PathBuf, slice};
5
6
7
8/// A safe way to send an [`OsString`] (or [`PathBuf`]) across an abi/ffi boundary. Unlike [`OsString`] and [`OsStr`], it has an encoding that will not change based on the compiler version, and it uses `#[repr(C)]`.
9///
10/// Note: there is no [`OsStr`] equivalent because copying the inner data may be necessary
11// Note: this is just `Vec<EncodingWidth>` but as `#[repr(C)]` and with no mutability
12#[repr(C)]
13pub struct StableOsString {
14	pub(crate) data: *mut EncodingWidth,
15	pub(crate) len: usize,
16	pub(crate) cap: usize,
17}
18
19impl StableOsString {
20	/// Converts this back into an [`OsString`]
21	#[inline]
22	#[must_use]
23	pub fn into_os_string(self) -> OsString {
24		let data = self.into_vec();
25		unsafe { OsString::from_raw_stable_encoding(data) }
26	}
27	/// Clones this into an [`OsString`]
28	#[inline]
29	#[must_use]
30	pub fn to_os_string(&self) -> OsString {
31		let data = self.as_slice();
32		unsafe { OsString::from_raw_stable_encoding(data) }
33	}
34
35	/// Converts this into a [`PathBuf`]
36	#[inline]
37	#[must_use]
38	pub fn into_path_buf(self) -> PathBuf {
39		PathBuf::from(self.into_os_string())
40	}
41
42	/// Clones this a [`PathBuf`]
43	#[inline]
44	#[must_use]
45	pub fn to_path_buf(&self) -> PathBuf {
46		PathBuf::from(self.to_os_string())
47	}
48
49	/// Constructs a new [`StableOsString`] from raw data.
50	///
51	/// # Safety
52	///
53	/// The given bytes must be compatible with the target platform's [`OsStr`] encoding (reminder: this crate only make it safe to pass data between different rust versions)
54	#[inline]
55	#[must_use]
56	pub unsafe fn from_vec(data: Vec<EncodingWidth>) -> Self {
57		let (data, len, cap) = data.into_raw_parts();
58		Self { data, len, cap }
59	}
60
61	/// Converts self back into raw data.
62	#[inline]
63	#[must_use]
64	pub fn into_vec(self) -> Vec<EncodingWidth> {
65		unsafe {
66			let data = self.make_vec_view();
67			std::mem::forget(self);
68			data
69		}
70	}
71
72	/// # Safety
73	///
74	/// This creates a second owner of [`Self::data`], so one owner must be leaked to avoid a double free
75	#[inline]
76	pub(crate) unsafe fn make_vec_view(&self) -> Vec<EncodingWidth> {
77		unsafe { Vec::from_raw_parts(self.data, self.len, self.cap) }
78	}
79
80	/// Creates a view of the inner data as a slice of [`EncodingWidth`]
81	#[inline]
82	#[must_use]
83	pub const fn as_slice(&self) -> &[EncodingWidth] {
84		unsafe { slice::from_raw_parts(self.data, self.len) }
85	}
86
87	/// Creates a view of the inner data as a slice of [`EncodingWidth`]
88	///
89	/// # Safety
90	///
91	/// The data inside the returned slice must stay compatible with the OS's string encoding format
92	#[inline]
93	#[must_use]
94	pub const unsafe fn as_slice_mut(&mut self) -> &mut [EncodingWidth] {
95		unsafe { slice::from_raw_parts_mut(self.data, self.len) }
96	}
97}
98
99impl Drop for StableOsString {
100	#[inline]
101	fn drop(&mut self) {
102		unsafe {
103			drop(self.make_vec_view());
104		}
105	}
106}
107
108impl Deref for StableOsString {
109	type Target = [EncodingWidth];
110	#[inline]
111	fn deref(&self) -> &Self::Target {
112		self.as_slice()
113	}
114}
115
116
117
118impl fmt::Debug for StableOsString {
119	#[inline]
120	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121		fmt::Debug::fmt(self.as_slice(), f)
122	}
123}
124
125impl Default for StableOsString {
126	#[inline]
127	fn default() -> Self {
128		unsafe { Self::from_vec(vec![]) }
129	}
130}
131
132impl Clone for StableOsString {
133	#[inline]
134	fn clone(&self) -> Self {
135		let other_vec = self.as_slice().to_vec();
136		unsafe { Self::from_vec(other_vec) }
137	}
138}
139
140impl PartialEq for StableOsString {
141	#[inline]
142	fn eq(&self, other: &Self) -> bool {
143		self.as_slice() == other.as_slice()
144	}
145}
146
147impl Eq for StableOsString {}
148
149impl PartialOrd for StableOsString {
150	#[inline]
151	fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
152		Some(self.cmp(other))
153	}
154}
155
156impl Ord for StableOsString {
157	#[inline]
158	fn cmp(&self, other: &Self) -> std::cmp::Ordering {
159		self.to_os_string().cmp(&other.to_os_string())
160	}
161}
162
163impl Hash for StableOsString {
164	fn hash<H: std::hash::Hasher>(&self, _state: &mut H) {
165		panic!(
166			"The type StableOsString should not be directly hashed, use either `.deref().hash()` or `.to_os_string().hash()`"
167		);
168	}
169}