Skip to main content

pyo3/conversions/std/
osstr.rs

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#[cfg(feature = "experimental-inspect")]
10use crate::type_object::PyTypeInfo;
11use crate::types::PyString;
12#[cfg(any(unix, target_os = "emscripten"))]
13use crate::types::{PyBytes, PyBytesMethods};
14use crate::{Borrowed, FromPyObject, PyAny, PyErr, Python};
15use alloc::borrow::Cow;
16use core::convert::Infallible;
17use std::ffi::{OsStr, OsString};
18#[cfg(any(unix, target_os = "emscripten"))]
19use std::os::unix::ffi::OsStrExt;
20#[cfg(windows)]
21use std::os::windows::ffi::OsStrExt;
22
23impl<'py> IntoPyObject<'py> for &OsStr {
24    type Target = PyString;
25    type Output = Bound<'py, Self::Target>;
26    type Error = Infallible;
27
28    #[cfg(feature = "experimental-inspect")]
29    const OUTPUT_TYPE: PyStaticExpr = PyString::TYPE_HINT;
30
31    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
32        // If the string is UTF-8, take the quick and easy shortcut
33        #[cfg(not(target_os = "wasi"))]
34        if let Some(valid_utf8_path) = self.to_str() {
35            return valid_utf8_path.into_pyobject(py);
36        }
37
38        #[cfg(target_os = "wasi")]
39        {
40            self.to_str()
41                .expect("wasi strings are UTF8")
42                .into_pyobject(py)
43        }
44
45        #[cfg(any(unix, target_os = "emscripten"))]
46        {
47            let bytes = self.as_bytes();
48            let ptr = bytes.as_ptr().cast();
49            let len = bytes.len() as ffi::Py_ssize_t;
50            // SAFETY: passing valid pointer to python API
51            unsafe {
52                // DecodeFSDefault automatically chooses an appropriate decoding mechanism to
53                // parse os strings losslessly (i.e. surrogateescape most of the time)
54                Ok(ffi::PyUnicode_DecodeFSDefaultAndSize(ptr, len)
55                    .assume_owned(py)
56                    .cast_into_unchecked())
57            }
58        }
59
60        #[cfg(windows)]
61        {
62            let wstr: Vec<u16> = self.encode_wide().collect();
63            // SAFETY: passing valid pointer to python API
64            unsafe {
65                // This will not panic because the data from encode_wide is well-formed Windows
66                // string data
67
68                Ok(
69                    ffi::PyUnicode_FromWideChar(wstr.as_ptr(), wstr.len() as ffi::Py_ssize_t)
70                        .assume_owned(py)
71                        .cast_into_unchecked(),
72                )
73            }
74        }
75    }
76}
77
78impl<'py> IntoPyObject<'py> for &&OsStr {
79    type Target = PyString;
80    type Output = Bound<'py, Self::Target>;
81    type Error = Infallible;
82
83    #[cfg(feature = "experimental-inspect")]
84    const OUTPUT_TYPE: PyStaticExpr = <&OsStr>::OUTPUT_TYPE;
85
86    #[inline]
87    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
88        (*self).into_pyobject(py)
89    }
90}
91
92impl FromPyObject<'_, '_> for OsString {
93    type Error = PyErr;
94
95    #[cfg(feature = "experimental-inspect")]
96    const INPUT_TYPE: PyStaticExpr = PyString::TYPE_HINT;
97
98    fn extract(ob: Borrowed<'_, '_, PyAny>) -> Result<Self, Self::Error> {
99        let pystring = ob.cast::<PyString>()?;
100
101        #[cfg(target_os = "wasi")]
102        {
103            Ok(pystring.to_cow()?.into_owned().into())
104        }
105
106        #[cfg(any(unix, target_os = "emscripten"))]
107        {
108            // Decode from Python's lossless bytes string representation back into raw bytes
109            // SAFETY: PyUnicode_EncodeFSDefault returns a new reference or null on error, known to
110            // be a `bytes` object, thread is attached to the interpreter
111            let fs_encoded_bytes = unsafe {
112                ffi::PyUnicode_EncodeFSDefault(pystring.as_ptr())
113                    .assume_owned_or_err(ob.py())?
114                    .cast_into_unchecked::<PyBytes>()
115            };
116
117            // Create an OsStr view into the raw bytes from Python
118            let os_str: &OsStr = OsStrExt::from_bytes(fs_encoded_bytes.as_bytes());
119
120            Ok(os_str.to_os_string())
121        }
122
123        #[cfg(windows)]
124        {
125            // Take the quick and easy shortcut if UTF-8
126            if let Ok(utf8_string) = pystring.to_cow() {
127                return Ok(utf8_string.into_owned().into());
128            }
129
130            // Get an owned allocated wide char buffer from PyString, which we have to deallocate
131            // ourselves
132            // SAFETY: passing valid pointer to python API
133            let size =
134                unsafe { ffi::PyUnicode_AsWideChar(pystring.as_ptr(), core::ptr::null_mut(), 0) };
135            crate::err::error_on_minusone(ob.py(), size)?;
136
137            debug_assert!(
138                size > 0,
139                "PyUnicode_AsWideChar should return at least 1 for null terminator"
140            );
141            let size = size - 1; // exclude null terminator
142
143            let mut buffer = vec![0; size as usize];
144            // SAFETY: passing valid pointer to python API
145            let bytes_read =
146                unsafe { ffi::PyUnicode_AsWideChar(pystring.as_ptr(), buffer.as_mut_ptr(), size) };
147            assert_eq!(bytes_read, size);
148
149            // Copy wide char buffer into OsString
150            let os_string = std::os::windows::ffi::OsStringExt::from_wide(&buffer);
151
152            Ok(os_string)
153        }
154    }
155}
156
157impl<'py> IntoPyObject<'py> for Cow<'_, OsStr> {
158    type Target = PyString;
159    type Output = Bound<'py, Self::Target>;
160    type Error = Infallible;
161
162    #[cfg(feature = "experimental-inspect")]
163    const OUTPUT_TYPE: PyStaticExpr = <&OsStr>::OUTPUT_TYPE;
164
165    #[inline]
166    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
167        (*self).into_pyobject(py)
168    }
169}
170
171impl<'py> IntoPyObject<'py> for &Cow<'_, OsStr> {
172    type Target = PyString;
173    type Output = Bound<'py, Self::Target>;
174    type Error = Infallible;
175
176    #[cfg(feature = "experimental-inspect")]
177    const OUTPUT_TYPE: PyStaticExpr = <&OsStr>::OUTPUT_TYPE;
178
179    #[inline]
180    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
181        (&**self).into_pyobject(py)
182    }
183}
184
185impl<'a> FromPyObject<'a, '_> for Cow<'a, OsStr> {
186    type Error = PyErr;
187
188    #[cfg(feature = "experimental-inspect")]
189    const INPUT_TYPE: PyStaticExpr = OsString::INPUT_TYPE;
190
191    fn extract(obj: Borrowed<'a, '_, PyAny>) -> Result<Self, Self::Error> {
192        #[cfg(any(Py_3_10, not(Py_LIMITED_API)))]
193        if let Ok(s) = obj.extract::<&str>() {
194            return Ok(Cow::Borrowed(s.as_ref()));
195        }
196
197        obj.extract::<OsString>().map(Cow::Owned)
198    }
199}
200
201impl<'py> IntoPyObject<'py> for OsString {
202    type Target = PyString;
203    type Output = Bound<'py, Self::Target>;
204    type Error = Infallible;
205
206    #[cfg(feature = "experimental-inspect")]
207    const OUTPUT_TYPE: PyStaticExpr = <&OsStr>::OUTPUT_TYPE;
208
209    #[inline]
210    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
211        self.as_os_str().into_pyobject(py)
212    }
213}
214
215impl<'py> IntoPyObject<'py> for &OsString {
216    type Target = PyString;
217    type Output = Bound<'py, Self::Target>;
218    type Error = Infallible;
219
220    #[cfg(feature = "experimental-inspect")]
221    const OUTPUT_TYPE: PyStaticExpr = <&OsStr>::OUTPUT_TYPE;
222
223    #[inline]
224    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
225        self.as_os_str().into_pyobject(py)
226    }
227}
228
229#[cfg(test)]
230mod tests {
231    #[cfg(target_os = "wasi")]
232    use crate::exceptions::PyFileNotFoundError;
233    use crate::types::{PyAnyMethods, PyString, PyStringMethods};
234    use crate::{Bound, BoundObject, IntoPyObject, Python};
235    use alloc::borrow::Cow;
236    use core::fmt::Debug;
237    use std::ffi::{OsStr, OsString};
238    #[cfg(any(unix, target_os = "emscripten"))]
239    use std::os::unix::ffi::OsStringExt;
240    #[cfg(windows)]
241    use std::os::windows::ffi::OsStringExt;
242
243    #[test]
244    #[cfg(any(unix, target_os = "emscripten"))]
245    fn test_non_utf8_conversion() {
246        Python::attach(|py| {
247            use std::os::unix::ffi::OsStrExt;
248
249            // this is not valid UTF-8
250            let payload = &[250, 251, 252, 253, 254, 255, 0, 255];
251            let os_str = OsStr::from_bytes(payload);
252
253            // do a roundtrip into Pythonland and back and compare
254            let py_str = os_str.into_pyobject(py).unwrap();
255            let os_str_2: OsString = py_str.extract().unwrap();
256            assert_eq!(os_str, os_str_2);
257        });
258    }
259
260    #[test]
261    #[cfg(target_os = "wasi")]
262    fn test_extract_non_utf8_wasi_should_error() {
263        Python::attach(|py| {
264            // Non utf-8 strings are not valid wasi paths
265            let open_result = py.run(c"open('\\udcff', 'rb')", None, None).unwrap_err();
266            assert!(
267                !open_result.is_instance_of::<PyFileNotFoundError>(py),
268                "Opening invalid utf8 will error with OSError, not FileNotFoundError"
269            );
270
271            // Create a Python string with not valid UTF-8: &[255]
272            let py_str = py.eval(c"'\\udcff'", None, None).unwrap();
273            assert!(
274                py_str.extract::<OsString>().is_err(),
275                "Extracting invalid UTF-8 as OsString should error"
276            );
277        });
278    }
279
280    #[test]
281    fn test_intopyobject_roundtrip() {
282        Python::attach(|py| {
283            fn test_roundtrip<'py, T>(py: Python<'py>, obj: T)
284            where
285                T: IntoPyObject<'py> + AsRef<OsStr> + Debug + Clone,
286                T::Error: Debug,
287            {
288                let pyobject = obj.clone().into_pyobject(py).unwrap().into_any();
289                let pystring = pyobject.as_borrowed().cast::<PyString>().unwrap();
290                assert_eq!(pystring.to_string_lossy(), obj.as_ref().to_string_lossy());
291                let roundtripped_obj: OsString = pystring.extract().unwrap();
292                assert_eq!(obj.as_ref(), roundtripped_obj.as_os_str());
293            }
294            let os_str = OsStr::new("Hello\0\n🐍");
295            test_roundtrip::<&OsStr>(py, os_str);
296            test_roundtrip::<Cow<'_, OsStr>>(py, Cow::Borrowed(os_str));
297            test_roundtrip::<Cow<'_, OsStr>>(py, Cow::Owned(os_str.to_os_string()));
298            test_roundtrip::<OsString>(py, os_str.to_os_string());
299        });
300    }
301
302    #[test]
303    #[cfg(windows)]
304    fn test_windows_non_utf8_osstring_roundtrip() {
305        use std::os::windows::ffi::{OsStrExt, OsStringExt};
306
307        Python::attach(|py| {
308            // Example: Unpaired surrogate (0xD800) is not valid UTF-8, but valid in Windows OsString
309            let wide: &[u16] = &['A' as u16, 0xD800, 'B' as u16]; // 'A', unpaired surrogate, 'B'
310            let os_str = OsString::from_wide(wide);
311
312            assert_eq!(os_str.to_string_lossy(), "A�B");
313
314            // This cannot be represented as UTF-8, so .to_str() would return None
315            assert!(os_str.to_str().is_none());
316
317            // Convert to Python and back
318            let py_str = os_str.as_os_str().into_pyobject(py).unwrap();
319            let os_str_2 = py_str.extract::<OsString>().unwrap();
320
321            // The roundtrip should preserve the original wide data
322            assert_eq!(os_str, os_str_2);
323
324            // Show that encode_wide is necessary: direct UTF-8 conversion would lose information
325            let encoded: Vec<u16> = os_str.encode_wide().collect();
326            assert_eq!(encoded, wide);
327        });
328    }
329
330    #[test]
331    fn test_extract_cow() {
332        Python::attach(|py| {
333            fn test_extract<'py, T>(py: Python<'py>, input: &T, is_borrowed: bool)
334            where
335                for<'a> &'a T: IntoPyObject<'py, Output = Bound<'py, PyString>>,
336                for<'a> <&'a T as IntoPyObject<'py>>::Error: Debug,
337                T: AsRef<OsStr> + ?Sized,
338            {
339                let pystring = input.into_pyobject(py).unwrap();
340                let cow: Cow<'_, OsStr> = pystring.extract().unwrap();
341                assert_eq!(cow, input.as_ref());
342                assert_eq!(is_borrowed, matches!(cow, Cow::Borrowed(_)));
343            }
344
345            // On Python 3.10+ or when not using the limited API, we can borrow strings from python
346            let can_borrow_str = cfg!(any(Py_3_10, not(Py_LIMITED_API)));
347            // This can be borrowed because it is valid UTF-8
348            test_extract::<str>(py, "Hello\0\n🐍", can_borrow_str);
349            test_extract::<str>(py, "Hello, world!", can_borrow_str);
350
351            #[cfg(windows)]
352            let os_str = {
353                // 'A', unpaired surrogate, 'B'
354                OsString::from_wide(&['A' as u16, 0xD800, 'B' as u16])
355            };
356
357            #[cfg(any(unix, target_os = "emscripten"))]
358            let os_str = { OsString::from_vec(vec![250, 251, 252, 253, 254, 255, 0, 255]) };
359
360            // This cannot be borrowed because it is not valid UTF-8
361            #[cfg(any(windows, unix, target_os = "emscripten"))]
362            test_extract::<OsStr>(py, &os_str, false);
363        });
364    }
365}