stable_osstring_encoding/
stable_os_string.rs1use crate::{EncodingWidth, FromRawStableEncoding};
2use std::{ffi::OsString, fmt, hash, path::PathBuf, slice};
3
4
5
6#[repr(C)]
11pub struct StableOsString {
12 pub(crate) data: *mut EncodingWidth,
13 pub(crate) len: usize,
14 pub(crate) cap: usize,
15}
16
17impl StableOsString {
18 #[inline]
20 #[must_use]
21 pub fn into_os_string(self) -> OsString {
22 let data = self.into_vec();
23 unsafe { OsString::from_raw_stable_encoding(data) }
24 }
25
26 #[inline]
28 #[must_use]
29 pub fn into_path_buf(self) -> PathBuf {
30 PathBuf::from(self.into_os_string())
31 }
32
33 #[inline]
39 #[must_use]
40 pub unsafe fn from_vec(data: Vec<EncodingWidth>) -> Self {
41 let (data, len, cap) = data.into_raw_parts();
42 Self { data, len, cap }
43 }
44
45 #[inline]
47 #[must_use]
48 pub fn into_vec(self) -> Vec<EncodingWidth> {
49 unsafe {
50 let data = self.make_vec();
51 std::mem::forget(self);
52 data
53 }
54 }
55
56 #[inline]
60 pub(crate) unsafe fn make_vec(&self) -> Vec<EncodingWidth> {
61 unsafe { Vec::from_raw_parts(self.data, self.len, self.cap) }
62 }
63
64 #[inline]
65 pub(crate) const fn as_slice(&self) -> &[EncodingWidth] {
66 unsafe { slice::from_raw_parts(self.data, self.len) }
67 }
68}
69
70impl Drop for StableOsString {
71 fn drop(&mut self) {
72 unsafe {
73 drop(self.make_vec());
74 }
75 }
76}
77
78impl Default for StableOsString {
79 fn default() -> Self {
80 unsafe { Self::from_vec(vec![]) }
81 }
82}
83
84impl Eq for StableOsString {}
85
86impl PartialEq for StableOsString {
87 fn eq(&self, other: &Self) -> bool {
88 self.as_slice() == other.as_slice()
89 }
90}
91
92impl hash::Hash for StableOsString {
93 fn hash<H: hash::Hasher>(&self, state: &mut H) {
94 self.as_slice().hash(state);
95 }
96}
97
98impl fmt::Debug for StableOsString {
99 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100 fmt::Debug::fmt(self.as_slice(), f)
101 }
102}
103
104impl Clone for StableOsString {
105 fn clone(&self) -> Self {
106 let other_vec = self.as_slice().to_vec();
107 unsafe { Self::from_vec(other_vec) }
108 }
109}