1use crate::conversion::IntoPyObject;
2#[cfg(not(target_os = "wasi"))]
3use crate::ffi;
4#[cfg(not(target_os = "wasi"))]
5use crate::ffi_ptr_ext::FfiPtrExt;
6#[cfg(feature = "experimental-inspect")]
7use crate::inspect::PyStaticExpr;
8use crate::instance::Bound;
9#[allow(unused_imports, reason = "conditionally used")]
10use crate::platform::prelude::*;
11#[cfg(feature = "experimental-inspect")]
12use crate::type_object::PyTypeInfo;
13use crate::types::PyString;
14#[cfg(any(unix, target_os = "emscripten"))]
15use crate::types::{PyBytes, PyBytesMethods};
16use crate::{Borrowed, FromPyObject, PyAny, PyErr, Python};
17use alloc::borrow::Cow;
18use core::convert::Infallible;
19use std::ffi::{OsStr, OsString};
20#[cfg(any(unix, target_os = "emscripten"))]
21use std::os::unix::ffi::OsStrExt;
22#[cfg(windows)]
23use std::os::windows::ffi::OsStrExt;
24
25impl<'py> IntoPyObject<'py> for &OsStr {
26 type Target = PyString;
27 type Output = Bound<'py, Self::Target>;
28 type Error = Infallible;
29
30 #[cfg(feature = "experimental-inspect")]
31 const OUTPUT_TYPE: PyStaticExpr = PyString::TYPE_HINT;
32
33 fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
34 #[cfg(not(target_os = "wasi"))]
36 if let Some(valid_utf8_path) = self.to_str() {
37 return valid_utf8_path.into_pyobject(py);
38 }
39
40 #[cfg(target_os = "wasi")]
41 {
42 self.to_str()
43 .expect("wasi strings are UTF8")
44 .into_pyobject(py)
45 }
46
47 #[cfg(any(unix, target_os = "emscripten"))]
48 {
49 let bytes = self.as_bytes();
50 let ptr = bytes.as_ptr().cast();
51 let len = bytes.len() as ffi::Py_ssize_t;
52 unsafe {
54 Ok(ffi::PyUnicode_DecodeFSDefaultAndSize(ptr, len)
57 .assume_owned(py)
58 .cast_into_unchecked())
59 }
60 }
61
62 #[cfg(windows)]
63 {
64 let wstr: Vec<u16> = self.encode_wide().collect();
65 unsafe {
67 Ok(
71 ffi::PyUnicode_FromWideChar(wstr.as_ptr(), wstr.len() as ffi::Py_ssize_t)
72 .assume_owned(py)
73 .cast_into_unchecked(),
74 )
75 }
76 }
77 }
78}
79
80impl<'py> IntoPyObject<'py> for &&OsStr {
81 type Target = PyString;
82 type Output = Bound<'py, Self::Target>;
83 type Error = Infallible;
84
85 #[cfg(feature = "experimental-inspect")]
86 const OUTPUT_TYPE: PyStaticExpr = <&OsStr>::OUTPUT_TYPE;
87
88 #[inline]
89 fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
90 (*self).into_pyobject(py)
91 }
92}
93
94impl FromPyObject<'_, '_> for OsString {
95 type Error = PyErr;
96
97 #[cfg(feature = "experimental-inspect")]
98 const INPUT_TYPE: PyStaticExpr = PyString::TYPE_HINT;
99
100 fn extract(ob: Borrowed<'_, '_, PyAny>) -> Result<Self, Self::Error> {
101 let pystring = ob.cast::<PyString>()?;
102
103 #[cfg(target_os = "wasi")]
104 {
105 Ok(pystring.to_cow()?.into_owned().into())
106 }
107
108 #[cfg(any(unix, target_os = "emscripten"))]
109 {
110 let fs_encoded_bytes = unsafe {
114 ffi::PyUnicode_EncodeFSDefault(pystring.as_ptr())
115 .assume_owned_or_err(ob.py())?
116 .cast_into_unchecked::<PyBytes>()
117 };
118
119 let os_str: &OsStr = OsStrExt::from_bytes(fs_encoded_bytes.as_bytes());
121
122 Ok(os_str.to_os_string())
123 }
124
125 #[cfg(windows)]
126 {
127 if let Ok(utf8_string) = pystring.to_cow() {
129 return Ok(utf8_string.into_owned().into());
130 }
131
132 let size =
136 unsafe { ffi::PyUnicode_AsWideChar(pystring.as_ptr(), core::ptr::null_mut(), 0) };
137 crate::err::error_on_negative(ob.py(), size)?;
138
139 debug_assert!(
140 size > 0,
141 "PyUnicode_AsWideChar should return at least 1 for null terminator"
142 );
143 let size = size - 1; let mut buffer = vec![0; size as usize];
146 let bytes_read =
148 unsafe { ffi::PyUnicode_AsWideChar(pystring.as_ptr(), buffer.as_mut_ptr(), size) };
149 assert_eq!(bytes_read, size);
150
151 let os_string = std::os::windows::ffi::OsStringExt::from_wide(&buffer);
153
154 Ok(os_string)
155 }
156 }
157}
158
159impl<'py> IntoPyObject<'py> for Cow<'_, OsStr> {
160 type Target = PyString;
161 type Output = Bound<'py, Self::Target>;
162 type Error = Infallible;
163
164 #[cfg(feature = "experimental-inspect")]
165 const OUTPUT_TYPE: PyStaticExpr = <&OsStr>::OUTPUT_TYPE;
166
167 #[inline]
168 fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
169 (*self).into_pyobject(py)
170 }
171}
172
173impl<'py> IntoPyObject<'py> for &Cow<'_, OsStr> {
174 type Target = PyString;
175 type Output = Bound<'py, Self::Target>;
176 type Error = Infallible;
177
178 #[cfg(feature = "experimental-inspect")]
179 const OUTPUT_TYPE: PyStaticExpr = <&OsStr>::OUTPUT_TYPE;
180
181 #[inline]
182 fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
183 (&**self).into_pyobject(py)
184 }
185}
186
187impl<'a> FromPyObject<'a, '_> for Cow<'a, OsStr> {
188 type Error = PyErr;
189
190 #[cfg(feature = "experimental-inspect")]
191 const INPUT_TYPE: PyStaticExpr = OsString::INPUT_TYPE;
192
193 fn extract(obj: Borrowed<'a, '_, PyAny>) -> Result<Self, Self::Error> {
194 #[cfg(any(Py_3_10, not(Py_LIMITED_API)))]
195 if let Ok(s) = obj.extract::<&str>() {
196 return Ok(Cow::Borrowed(s.as_ref()));
197 }
198
199 obj.extract::<OsString>().map(Cow::Owned)
200 }
201}
202
203impl<'py> IntoPyObject<'py> for OsString {
204 type Target = PyString;
205 type Output = Bound<'py, Self::Target>;
206 type Error = Infallible;
207
208 #[cfg(feature = "experimental-inspect")]
209 const OUTPUT_TYPE: PyStaticExpr = <&OsStr>::OUTPUT_TYPE;
210
211 #[inline]
212 fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
213 self.as_os_str().into_pyobject(py)
214 }
215}
216
217impl<'py> IntoPyObject<'py> for &OsString {
218 type Target = PyString;
219 type Output = Bound<'py, Self::Target>;
220 type Error = Infallible;
221
222 #[cfg(feature = "experimental-inspect")]
223 const OUTPUT_TYPE: PyStaticExpr = <&OsStr>::OUTPUT_TYPE;
224
225 #[inline]
226 fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
227 self.as_os_str().into_pyobject(py)
228 }
229}
230
231#[cfg(test)]
232mod tests {
233 #[cfg(target_os = "wasi")]
234 use crate::exceptions::PyFileNotFoundError;
235 #[allow(unused_imports, reason = "conditionally used")]
236 use crate::platform::prelude::*;
237 use crate::types::{PyAnyMethods, PyString, PyStringMethods};
238 use crate::{Bound, BoundObject, IntoPyObject, Python};
239 use alloc::borrow::Cow;
240 use core::fmt::Debug;
241 use std::ffi::{OsStr, OsString};
242 #[cfg(any(unix, target_os = "emscripten"))]
243 use std::os::unix::ffi::OsStringExt;
244 #[cfg(windows)]
245 use std::os::windows::ffi::OsStringExt;
246
247 #[test]
248 #[cfg(any(unix, target_os = "emscripten"))]
249 fn test_non_utf8_conversion() {
250 Python::attach(|py| {
251 use std::os::unix::ffi::OsStrExt;
252
253 let payload = &[250, 251, 252, 253, 254, 255, 0, 255];
255 let os_str = OsStr::from_bytes(payload);
256
257 let py_str = os_str.into_pyobject(py).unwrap();
259 let os_str_2: OsString = py_str.extract().unwrap();
260 assert_eq!(os_str, os_str_2);
261 });
262 }
263
264 #[test]
265 #[cfg(target_os = "wasi")]
266 fn test_extract_non_utf8_wasi_should_error() {
267 Python::attach(|py| {
268 let open_result = py.run(c"open('\\udcff', 'rb')", None, None).unwrap_err();
270 assert!(
271 !open_result.is_instance_of::<PyFileNotFoundError>(py),
272 "Opening invalid utf8 will error with OSError, not FileNotFoundError"
273 );
274
275 let py_str = py.eval(c"'\\udcff'", None, None).unwrap();
277 assert!(
278 py_str.extract::<OsString>().is_err(),
279 "Extracting invalid UTF-8 as OsString should error"
280 );
281 });
282 }
283
284 #[test]
285 fn test_intopyobject_roundtrip() {
286 Python::attach(|py| {
287 fn test_roundtrip<'py, T>(py: Python<'py>, obj: T)
288 where
289 T: IntoPyObject<'py> + AsRef<OsStr> + Debug + Clone,
290 T::Error: Debug,
291 {
292 let pyobject = obj.clone().into_pyobject(py).unwrap().into_any();
293 let pystring = pyobject.as_borrowed().cast::<PyString>().unwrap();
294 assert_eq!(pystring.to_string_lossy(), obj.as_ref().to_string_lossy());
295 let roundtripped_obj: OsString = pystring.extract().unwrap();
296 assert_eq!(obj.as_ref(), roundtripped_obj.as_os_str());
297 }
298 let os_str = OsStr::new("Hello\0\n🐍");
299 test_roundtrip::<&OsStr>(py, os_str);
300 test_roundtrip::<Cow<'_, OsStr>>(py, Cow::Borrowed(os_str));
301 test_roundtrip::<Cow<'_, OsStr>>(py, Cow::Owned(os_str.to_os_string()));
302 test_roundtrip::<OsString>(py, os_str.to_os_string());
303 });
304 }
305
306 #[test]
307 #[cfg(windows)]
308 fn test_windows_non_utf8_osstring_roundtrip() {
309 use std::os::windows::ffi::{OsStrExt, OsStringExt};
310
311 Python::attach(|py| {
312 let wide: &[u16] = &['A' as u16, 0xD800, 'B' as u16]; let os_str = OsString::from_wide(wide);
315
316 assert_eq!(os_str.to_string_lossy(), "A�B");
317
318 assert!(os_str.to_str().is_none());
320
321 let py_str = os_str.as_os_str().into_pyobject(py).unwrap();
323 let os_str_2 = py_str.extract::<OsString>().unwrap();
324
325 assert_eq!(os_str, os_str_2);
327
328 let encoded: Vec<u16> = os_str.encode_wide().collect();
330 assert_eq!(encoded, wide);
331 });
332 }
333
334 #[test]
335 fn test_extract_cow() {
336 Python::attach(|py| {
337 fn test_extract<'py, T>(py: Python<'py>, input: &T, is_borrowed: bool)
338 where
339 for<'a> &'a T: IntoPyObject<'py, Output = Bound<'py, PyString>>,
340 for<'a> <&'a T as IntoPyObject<'py>>::Error: Debug,
341 T: AsRef<OsStr> + ?Sized,
342 {
343 let pystring = input.into_pyobject(py).unwrap();
344 let cow: Cow<'_, OsStr> = pystring.extract().unwrap();
345 assert_eq!(cow, input.as_ref());
346 assert_eq!(is_borrowed, matches!(cow, Cow::Borrowed(_)));
347 }
348
349 let can_borrow_str = cfg!(any(Py_3_10, not(Py_LIMITED_API)));
351 test_extract::<str>(py, "Hello\0\n🐍", can_borrow_str);
353 test_extract::<str>(py, "Hello, world!", can_borrow_str);
354
355 #[cfg(windows)]
356 let os_str = {
357 OsString::from_wide(&['A' as u16, 0xD800, 'B' as u16])
359 };
360
361 #[cfg(any(unix, target_os = "emscripten"))]
362 let os_str = { OsString::from_vec(vec![250, 251, 252, 253, 254, 255, 0, 255]) };
363
364 #[cfg(any(windows, unix, target_os = "emscripten"))]
366 test_extract::<OsStr>(py, &os_str, false);
367 });
368 }
369}