Merge pull request #637 from Alexander-N/bytes

Implement conversion traits for PyBytes
This commit is contained in:
Yuji Kanagawa 2019-10-21 00:21:44 +09:00 committed by GitHub
commit 6a89a904e3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 44 additions and 0 deletions

View File

@ -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};
@ -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();

22
tests/test_bytes.rs Normal file
View File

@ -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'"
);
}