pyo3/conversions/std/
path.rs

1use crate::ffi_ptr_ext::FfiPtrExt;
2use crate::instance::Bound;
3use crate::types::any::PyAnyMethods;
4use crate::{ffi, FromPyObject, IntoPy, PyAny, PyObject, PyResult, Python, ToPyObject};
5use std::borrow::Cow;
6use std::ffi::OsString;
7use std::path::{Path, PathBuf};
8
9impl ToPyObject for Path {
10    fn to_object(&self, py: Python<'_>) -> PyObject {
11        self.as_os_str().to_object(py)
12    }
13}
14
15// See osstr.rs for why there's no FromPyObject impl for &Path
16
17impl FromPyObject<'_> for PathBuf {
18    fn extract_bound(ob: &Bound<'_, PyAny>) -> PyResult<Self> {
19        // We use os.fspath to get the underlying path as bytes or str
20        let path = unsafe { ffi::PyOS_FSPath(ob.as_ptr()).assume_owned_or_err(ob.py())? };
21        Ok(path.extract::<OsString>()?.into())
22    }
23}
24
25impl<'a> IntoPy<PyObject> for &'a Path {
26    #[inline]
27    fn into_py(self, py: Python<'_>) -> PyObject {
28        self.as_os_str().to_object(py)
29    }
30}
31
32impl<'a> ToPyObject for Cow<'a, Path> {
33    #[inline]
34    fn to_object(&self, py: Python<'_>) -> PyObject {
35        self.as_os_str().to_object(py)
36    }
37}
38
39impl<'a> IntoPy<PyObject> for Cow<'a, Path> {
40    #[inline]
41    fn into_py(self, py: Python<'_>) -> PyObject {
42        self.to_object(py)
43    }
44}
45
46impl ToPyObject for PathBuf {
47    #[inline]
48    fn to_object(&self, py: Python<'_>) -> PyObject {
49        self.as_os_str().to_object(py)
50    }
51}
52
53impl IntoPy<PyObject> for PathBuf {
54    fn into_py(self, py: Python<'_>) -> PyObject {
55        self.into_os_string().to_object(py)
56    }
57}
58
59impl<'a> IntoPy<PyObject> for &'a PathBuf {
60    fn into_py(self, py: Python<'_>) -> PyObject {
61        self.as_os_str().to_object(py)
62    }
63}
64
65#[cfg(test)]
66mod tests {
67    use crate::types::{PyAnyMethods, PyStringMethods};
68    use crate::{types::PyString, IntoPy, PyObject, Python, ToPyObject};
69    use std::borrow::Cow;
70    use std::fmt::Debug;
71    use std::path::{Path, PathBuf};
72
73    #[test]
74    #[cfg(not(windows))]
75    fn test_non_utf8_conversion() {
76        Python::with_gil(|py| {
77            use std::ffi::OsStr;
78            #[cfg(not(target_os = "wasi"))]
79            use std::os::unix::ffi::OsStrExt;
80            #[cfg(target_os = "wasi")]
81            use std::os::wasi::ffi::OsStrExt;
82
83            // this is not valid UTF-8
84            let payload = &[250, 251, 252, 253, 254, 255, 0, 255];
85            let path = Path::new(OsStr::from_bytes(payload));
86
87            // do a roundtrip into Pythonland and back and compare
88            let py_str: PyObject = path.into_py(py);
89            let path_2: PathBuf = py_str.extract(py).unwrap();
90            assert_eq!(path, path_2);
91        });
92    }
93
94    #[test]
95    fn test_topyobject_roundtrip() {
96        Python::with_gil(|py| {
97            fn test_roundtrip<T: ToPyObject + AsRef<Path> + Debug>(py: Python<'_>, obj: T) {
98                let pyobject = obj.to_object(py);
99                let pystring = pyobject.downcast_bound::<PyString>(py).unwrap();
100                assert_eq!(pystring.to_string_lossy(), obj.as_ref().to_string_lossy());
101                let roundtripped_obj: PathBuf = pystring.extract().unwrap();
102                assert_eq!(obj.as_ref(), roundtripped_obj.as_path());
103            }
104            let path = Path::new("Hello\0\nšŸ");
105            test_roundtrip::<&Path>(py, path);
106            test_roundtrip::<Cow<'_, Path>>(py, Cow::Borrowed(path));
107            test_roundtrip::<Cow<'_, Path>>(py, Cow::Owned(path.to_path_buf()));
108            test_roundtrip::<PathBuf>(py, path.to_path_buf());
109        });
110    }
111
112    #[test]
113    fn test_intopy_roundtrip() {
114        Python::with_gil(|py| {
115            fn test_roundtrip<T: IntoPy<PyObject> + AsRef<Path> + Debug + Clone>(
116                py: Python<'_>,
117                obj: T,
118            ) {
119                let pyobject = obj.clone().into_py(py);
120                let pystring = pyobject.downcast_bound::<PyString>(py).unwrap();
121                assert_eq!(pystring.to_string_lossy(), obj.as_ref().to_string_lossy());
122                let roundtripped_obj: PathBuf = pystring.extract().unwrap();
123                assert_eq!(obj.as_ref(), roundtripped_obj.as_path());
124            }
125            let path = Path::new("Hello\0\nšŸ");
126            test_roundtrip::<&Path>(py, path);
127            test_roundtrip::<PathBuf>(py, path.to_path_buf());
128            test_roundtrip::<&PathBuf>(py, &path.to_path_buf());
129        })
130    }
131}