Skip to content

Commit

Permalink
Add IntoPy impl for Cow<[u8]> which is symmetric to its FromPyObject …
Browse files Browse the repository at this point in the history
…impl.
  • Loading branch information
adamreichold committed Jan 21, 2023
1 parent 8207a77 commit 198d684
Showing 1 changed file with 22 additions and 1 deletion.
23 changes: 22 additions & 1 deletion src/types/bytes.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{ffi, AsPyPointer, FromPyObject, Py, PyAny, PyResult, Python};
use crate::{ffi, AsPyPointer, FromPyObject, IntoPy, Py, PyAny, PyResult, Python};
use std::borrow::Cow;
use std::ops::Index;
use std::os::raw::c_char;
Expand Down Expand Up @@ -140,10 +140,21 @@ impl<'source> FromPyObject<'source> for Cow<'source, [u8]> {
}
}

impl IntoPy<Py<PyAny>> for Cow<'_, [u8]> {
fn into_py(self, py: Python<'_>) -> Py<PyAny> {
match self {
Cow::Borrowed(slice) => PyBytes::new(py, slice).into(),
Cow::Owned(vec) => PyByteArray::new(py, &vec).into(),
}
}
}

#[cfg(test)]
mod tests {
use super::*;

use crate::types::IntoPyDict;

#[test]
fn test_bytes_index() {
Python::with_gil(|py| {
Expand Down Expand Up @@ -205,6 +216,16 @@ mod tests {
something_else_entirely
.extract::<Cow<'_, [u8]>>()
.unwrap_err();

let cow = Cow::<[u8]>::Borrowed(b"foobar").into_py(py);
let locals = [("cow", cow)].into_py_dict(py);
py.run("assert isinstance(cow, bytes)", Some(locals), None)
.unwrap();

let cow = Cow::<[u8]>::Owned(b"foobar".to_vec()).into_py(py);
let locals = [("cow", cow)].into_py_dict(py);
py.run("assert isinstance(cow, bytearray)", Some(locals), None)
.unwrap();
});
}
}

0 comments on commit 198d684

Please sign in to comment.