use crate::{EncodingWidth, FromRawStableEncoding};
#[cfg(doc)]
use std::ffi::OsStr;
use std::{ffi::OsString, fmt, hash::Hash, ops::Deref, 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 to_os_string(&self) -> OsString {
let data = self.as_slice();
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 fn to_path_buf(&self) -> PathBuf {
PathBuf::from(self.to_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_view();
std::mem::forget(self);
data
}
}
#[inline]
pub(crate) unsafe fn make_vec_view(&self) -> Vec<EncodingWidth> {
unsafe { Vec::from_raw_parts(self.data, self.len, self.cap) }
}
#[inline]
#[must_use]
pub const fn as_slice(&self) -> &[EncodingWidth] {
unsafe { slice::from_raw_parts(self.data, self.len) }
}
#[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()`"
);
}
}