diff --git a/newsfragments/3729.added.md b/newsfragments/3729.added.md new file mode 100644 index 00000000000..44f06b46851 --- /dev/null +++ b/newsfragments/3729.added.md @@ -0,0 +1 @@ +Implement `IntoPy` and `ToPyObject` for `Box`. diff --git a/src/conversion.rs b/src/conversion.rs index 429ca9e8779..7f2cc0afb96 100644 --- a/src/conversion.rs +++ b/src/conversion.rs @@ -243,6 +243,21 @@ impl ToPyObject for &'_ T { } } +impl ToPyObject for Box { + fn to_object(&self, py: Python<'_>) -> PyObject { + self.as_ref().to_object(py) + } +} + +impl IntoPy for Box +where + T: IntoPy, +{ + fn into_py(self, py: Python<'_>) -> PyObject { + (*self).into_py(py) + } +} + /// `Option::Some` is converted like `T`. /// `Option::None` is converted to Python `None`. impl ToPyObject for Option @@ -578,7 +593,7 @@ mod test_no_clone {} #[cfg(test)] mod tests { - use crate::{PyObject, Python}; + use crate::{IntoPy, PyObject, Python, ToPyObject}; #[allow(deprecated)] mod deprecated { @@ -641,4 +656,22 @@ mod tests { assert_eq!(none.get_refcnt(), ref_cnt); }); } + + #[test] + fn test_box_topyobject() { + let s: Box = "test".into(); + + let obj = Python::with_gil(|py| s.to_object(py)); + + assert_eq!(&obj.to_string(), "test") + } + + #[test] + fn test_box_intopy() { + let s: Box = "test".into(); + + let obj: PyObject = Python::with_gil(|py| s.into_py(py)); + + assert_eq!(&obj.to_string(), "test") + } }