stable-osstring-encoding 2.0.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};
use std::{ffi::OsString, fmt, hash, 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) }
	}

	/// Converts this into a `PathBuf`
	#[inline]
	#[must_use]
	pub fn into_path_buf(self) -> PathBuf {
		PathBuf::from(self.into_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();
			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(&self) -> Vec<EncodingWidth> {
		unsafe { Vec::from_raw_parts(self.data, self.len, self.cap) }
	}

	#[inline]
	pub(crate) const fn as_slice(&self) -> &[EncodingWidth] {
		unsafe { slice::from_raw_parts(self.data, self.len) }
	}
}

impl Drop for StableOsString {
	fn drop(&mut self) {
		unsafe {
			drop(self.make_vec());
		}
	}
}

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

impl Eq for StableOsString {}

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

impl hash::Hash for StableOsString {
	fn hash<H: hash::Hasher>(&self, state: &mut H) {
		self.as_slice().hash(state);
	}
}

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

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