Skip to main content

pyo3_object_store/
path.rs

1use object_store::path::Path;
2use pyo3::exceptions::PyValueError;
3use pyo3::prelude::*;
4use pyo3::pybacked::PyBackedStr;
5use pyo3::types::PyString;
6
7/// A Python-facing wrapper around a [`Path`].
8#[derive(Clone, Debug, Default, PartialEq)]
9pub struct PyPath(Path);
10
11impl<'py> FromPyObject<'_, 'py> for PyPath {
12    type Error = PyErr;
13
14    fn extract(obj: Borrowed<'_, 'py, PyAny>) -> Result<Self, Self::Error> {
15        let path = Path::parse(obj.extract::<PyBackedStr>()?)
16            .map_err(|err| PyValueError::new_err(format!("Could not parse path: {err}")))?;
17        Ok(Self(path))
18    }
19}
20
21impl PyPath {
22    /// Consume self and return the underlying [`Path`].
23    pub fn into_inner(self) -> Path {
24        self.0
25    }
26}
27
28impl<'py> IntoPyObject<'py> for PyPath {
29    type Target = PyString;
30    type Output = Bound<'py, PyString>;
31    type Error = PyErr;
32
33    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
34        Ok(PyString::new(py, self.0.as_ref()))
35    }
36}
37
38impl<'py> IntoPyObject<'py> for &PyPath {
39    type Target = PyString;
40    type Output = Bound<'py, PyString>;
41    type Error = PyErr;
42
43    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
44        Ok(PyString::new(py, self.0.as_ref()))
45    }
46}
47
48impl AsRef<Path> for PyPath {
49    fn as_ref(&self) -> &Path {
50        &self.0
51    }
52}
53
54impl From<PyPath> for Path {
55    fn from(value: PyPath) -> Self {
56        value.0
57    }
58}
59
60impl From<Path> for PyPath {
61    fn from(value: Path) -> Self {
62        Self(value)
63    }
64}