From eaf5dcaab77b70efa7d4913f666c4d28ff7c6be8 Mon Sep 17 00:00:00 2001 From: messense Date: Sun, 4 Jul 2021 13:14:50 +0800 Subject: [PATCH] Implement `IntoPy` for `&PathBuf` and `&OsString` --- CHANGELOG.md | 6 ++++++ src/conversions/osstr.rs | 7 +++++++ src/conversions/path.rs | 9 ++++++++- 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 469ab26a97c..ca5cf9238f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,12 @@ PyO3 versions, please see the [migration guide](https://pyo3.rs/main/migration.h The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Added + +- Implement `IntoPy` for `&PathBuf` and `&OsString`. [#1721](https://github.com/PyO3/pyo3/pull/1712) + ## [0.14.0] - 2021-07-03 ### Packaging diff --git a/src/conversions/osstr.rs b/src/conversions/osstr.rs index 466a4417b86..b05709b93fe 100644 --- a/src/conversions/osstr.rs +++ b/src/conversions/osstr.rs @@ -145,6 +145,12 @@ impl IntoPy for OsString { } } +impl<'a> IntoPy for &'a OsString { + fn into_py(self, py: Python) -> PyObject { + self.to_object(py) + } +} + #[cfg(test)] mod test { use crate::{types::PyString, IntoPy, PyObject, Python, ToPyObject}; @@ -205,6 +211,7 @@ mod test { let os_str = OsStr::new("Hello\0\nšŸ"); test_roundtrip::<&OsStr>(py, os_str); test_roundtrip::(py, os_str.to_os_string()); + test_roundtrip::<&OsString>(py, &os_str.to_os_string()); }) } } diff --git a/src/conversions/path.rs b/src/conversions/path.rs index 549164e6636..7fc34baf4c1 100644 --- a/src/conversions/path.rs +++ b/src/conversions/path.rs @@ -66,6 +66,12 @@ impl IntoPy for PathBuf { } } +impl<'a> IntoPy for &'a PathBuf { + fn into_py(self, py: Python) -> PyObject { + self.as_os_str().to_object(py) + } +} + #[cfg(test)] mod test { use crate::{types::PyString, IntoPy, PyObject, Python, ToPyObject}; @@ -120,11 +126,12 @@ mod test { let pystring: &PyString = pyobject.extract(py).unwrap(); assert_eq!(pystring.to_string_lossy(), obj.as_ref().to_string_lossy()); let roundtripped_obj: PathBuf = pystring.extract().unwrap(); - assert!(obj.as_ref() == roundtripped_obj.as_path()); + assert_eq!(obj.as_ref(), roundtripped_obj.as_path()); } let path = Path::new("Hello\0\nšŸ"); test_roundtrip::<&Path>(py, path); test_roundtrip::(py, path.to_path_buf()); + test_roundtrip::<&PathBuf>(py, &path.to_path_buf()); }) } }