stable-osstring-encoding 2.1.0

Converts OsString (and more) to and from raw data with an encoding that will not change based on the compiler version.
Documentation
use crate::{EncodingWidth, FromRawStableEncoding};
#[cfg(doc)]
use std::ffi::OsStr;
use std::{ffi::OsString, fmt, hash::Hash, ops::Deref, path::PathBuf, slice};



/// 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)]`.
///
/// Note: there is no [`OsStr`] equivalent because copying the inner data may be necessary
// Note: this is just `Vec<EncodingWidth>` but as `#[repr(C)]` and with no mutability
#[repr(C)]
pub struct StableOsString {
	pub(crate) data: *mut EncodingWidth,
	pub(crate) len: usize,
	pub(crate) cap: usize,
}

impl StableOsString {
	/// Converts this back into an [`OsString`]
	#[inline]
	#[must_use]
	pub fn into_os_string(self) -> OsString {
		let data = self.into_vec();
		unsafe { OsString::from_raw_stable_encoding(data) }
	}
	/// Clones this into an [`OsString`]
	#[inline]
	#[must_use]
	pub fn to_os_string(&self) -> OsString {
		let data = self.as_slice();
		unsafe { OsString::from_raw_stable_encoding(data) }
	}

	/// Converts this into a [`PathBuf`]
	#[inline]
	#[must_use]
	pub fn into_path_buf(self) -> PathBuf {
		PathBuf::from(self.into_os_string())
	}

	/// Clones this a [`PathBuf`]
	#[inline]
	#[must_use]
	pub fn to_path_buf(&self) -> PathBuf {
		PathBuf::from(self.to_os_string())
	}

	/// Constructs a new [`StableOsString`] from raw data.
	///
	/// # Safety
	///
	/// 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)
	#[inline]
	#[must_use]
	pub unsafe fn from_vec(data: Vec<EncodingWidth>) -> Self {
		let (data, len, cap) = data.into_raw_parts();
		Self { data, len, cap }
	}

	/// Converts self back into raw data.
	#[inline]
	#[must_use]
	pub fn into_vec(self) -> Vec<EncodingWidth> {
		unsafe {
			let data = self.make_vec_view();
			std::mem::forget(self);
			data
		}
	}

	/// # Safety
	///
	/// This creates a second owner of [`Self::data`], so one owner must be leaked to avoid a double free
	#[inline]
	pub(crate) unsafe fn make_vec_view(&self) -> Vec<EncodingWidth> {
		unsafe { Vec::from_raw_parts(self.data, self.len, self.cap) }
	}

	/// Creates a view of the inner data as a slice of [`EncodingWidth`]
	#[inline]
	#[must_use]
	pub const fn as_slice(&self) -> &[EncodingWidth] {
		unsafe { slice::from_raw_parts(self.data, self.len) }
	}

	/// Creates a view of the inner data as a slice of [`EncodingWidth`]
	///
	/// # Safety
	///
	/// The data inside the returned slice must stay compatible with the OS's string encoding format
	#[inline]
	#[must_use]
	pub const unsafe fn as_slice_mut(&mut self) -> &mut [EncodingWidth] {
		unsafe { slice::from_raw_parts_mut(self.data, self.len) }
	}
}

impl Drop for StableOsString {
	#[inline]
	fn drop(&mut self) {
		unsafe {
			drop(self.make_vec_view());
		}
	}
}

impl Deref for StableOsString {
	type Target = [EncodingWidth];
	#[inline]
	fn deref(&self) -> &Self::Target {
		self.as_slice()
	}
}



impl fmt::Debug for StableOsString {
	#[inline]
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		fmt::Debug::fmt(self.as_slice(), f)
	}
}

impl Default for StableOsString {
	#[inline]
	fn default() -> Self {
		unsafe { Self::from_vec(vec![]) }
	}
}

impl Clone for StableOsString {
	#[inline]
	fn clone(&self) -> Self {
		let other_vec = self.as_slice().to_vec();
		unsafe { Self::from_vec(other_vec) }
	}
}

impl PartialEq for StableOsString {
	#[inline]
	fn eq(&self, other: &Self) -> bool {
		self.as_slice() == other.as_slice()
	}
}

impl Eq for StableOsString {}

impl PartialOrd for StableOsString {
	#[inline]
	fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
		Some(self.cmp(other))
	}
}

impl Ord for StableOsString {
	#[inline]
	fn cmp(&self, other: &Self) -> std::cmp::Ordering {
		self.to_os_string().cmp(&other.to_os_string())
	}
}

impl Hash for StableOsString {
	fn hash<H: std::hash::Hasher>(&self, _state: &mut H) {
		panic!(
			"The type StableOsString should not be directly hashed, use either `.deref().hash()` or `.to_os_string().hash()`"
		);
	}
}