Skip to content

Commit

Permalink
Merge pull request #637 from Alexander-N/bytes
Browse files Browse the repository at this point in the history
Implement conversion traits for PyBytes
  • Loading branch information
kngwyu authored Oct 20, 2019
2 parents f6f607e + 69cbf1a commit 6a89a90
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/types/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,18 @@ impl<'source> FromPyObject<'source> for String {
}
}

impl<'a> FromPy<&'a [u8]> for PyObject {
fn from_py(other: &'a [u8], py: Python) -> Self {
PyBytes::new(py, other).to_object(py)
}
}

impl<'a> FromPyObject<'a> for &'a [u8] {
fn extract(obj: &'a PyAny) -> PyResult<Self> {
Ok(<PyBytes as PyTryFrom>::try_from(obj)?.as_bytes())
}
}

#[cfg(test)]
mod test {
use super::{PyBytes, PyString};
Expand Down Expand Up @@ -244,6 +256,16 @@ mod test {
assert_eq!(s, s2);
}

#[test]
fn test_extract_bytes() {
let gil = Python::acquire_gil();
let py = gil.python();

let py_bytes = py.eval("b'Hello Python'", None, None).unwrap();
let bytes: &[u8] = FromPyObject::extract(py_bytes).unwrap();
assert_eq!(bytes, b"Hello Python");
}

#[test]
fn test_as_bytes() {
let gil = Python::acquire_gil();
Expand Down
22 changes: 22 additions & 0 deletions tests/test_bytes.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
use pyo3::prelude::*;
use pyo3::wrap_pyfunction;

mod common;

#[pyfunction]
fn bytes_pybytes_conversion(bytes: &[u8]) -> &[u8] {
bytes
}

#[test]
fn test_pybytes_bytes_conversion() {
let gil = Python::acquire_gil();
let py = gil.python();

let bytes_pybytes_conversion = wrap_pyfunction!(bytes_pybytes_conversion)(py);
py_assert!(
py,
bytes_pybytes_conversion,
"bytes_pybytes_conversion(b'Hello World') == b'Hello World'"
);
}

0 comments on commit 6a89a90

Please sign in to comment.