use crate::{EncodingWidth, FromRawStableEncoding};
use std::{ffi::OsString, fmt, hash, path::PathBuf, slice};
#[repr(C)]
pub struct StableOsString {
pub(crate) data: *mut EncodingWidth,
pub(crate) len: usize,
pub(crate) cap: usize,
}
impl StableOsString {
#[inline]
#[must_use]
pub fn into_os_string(self) -> OsString {
let data = self.into_vec();
unsafe { OsString::from_raw_stable_encoding(data) }
}
#[inline]
#[must_use]
pub fn into_path_buf(self) -> PathBuf {
PathBuf::from(self.into_os_string())
}
#[inline]
#[must_use]
pub unsafe fn from_vec(data: Vec<EncodingWidth>) -> Self {
let (data, len, cap) = data.into_raw_parts();
Self { data, len, cap }
}
#[inline]
#[must_use]
pub fn into_vec(self) -> Vec<EncodingWidth> {
unsafe {
let data = self.make_vec();
std::mem::forget(self);
data
}
}
#[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) }
}
}