-
Notifications
You must be signed in to change notification settings - Fork 847
add bytes
conversion
#5111
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
kykosic
wants to merge
3
commits into
PyO3:main
Choose a base branch
from
kykosic:bytes
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
add bytes
conversion
#5111
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
Add bytes to/from python conversions. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,161 @@ | ||
#![cfg(feature = "bytes")] | ||
|
||
//! Conversions to and from [bytes](https://docs.rs/bytes/latest/bytes/)'s [`Bytes`] and | ||
//! [`BytesMut`] types. | ||
//! | ||
//! This is useful for efficiently converting Python's `bytes` and `bytearray` types efficiently. | ||
//! | ||
//! # Setup | ||
//! | ||
//! To use this feature, add in your **`Cargo.toml`**: | ||
//! | ||
//! ```toml | ||
//! [dependencies] | ||
#![doc = concat!("pyo3 = { version = \"", env!("CARGO_PKG_VERSION"), "\", features = [\"bytes\"] }")] | ||
//! bytes = "1.10" | ||
//! | ||
//! Note that you must use compatible versions of bytes and PyO3. | ||
//! | ||
//! # Example | ||
//! | ||
//! Rust code to create functions which return `Bytes` or take `Bytes` as arguements: | ||
//! | ||
//! ```rust,no_run | ||
//! use pyo3::prelude::*; | ||
//! | ||
//! #[pyfunction] | ||
//! fn get_message_bytes() -> Bytes { | ||
//! Bytes::from(b"Hello Python!".to_vec()) | ||
//! } | ||
//! | ||
//! #[pyfunction] | ||
//! fn num_bytes(bytes: Bytes) -> usize { | ||
//! bytes.len() | ||
//! } | ||
Comment on lines
+31
to
+34
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The example is not that great, the user should just use |
||
//! | ||
//! #[pymodule] | ||
//! fn my_module(m: &Bound<'_, PyModule>) -> PyResult<()> { | ||
//! m.add_function(wrap_pyfunction!(get_message_bytes, m)?)?; | ||
//! m.add_function(wrap_pyfunction!(num_bytes, m)?)?; | ||
//! Ok(()) | ||
//! } | ||
//! ``` | ||
//! | ||
//! Python code that calls these functions: | ||
//! | ||
//! ```python | ||
//! from my_module import get_message_bytes, num_bytes | ||
//! | ||
//! message = get_message_bytes() | ||
//! assert message == b"Hello Python!" | ||
//! | ||
//! size = num_bytes(message) | ||
//! assert size == 13 | ||
//! ``` | ||
use bytes::{Bytes, BytesMut}; | ||
|
||
use crate::conversion::IntoPyObject; | ||
use crate::exceptions::PyTypeError; | ||
use crate::instance::Bound; | ||
use crate::types::any::PyAnyMethods; | ||
use crate::types::{PyByteArray, PyByteArrayMethods, PyBytes, PyBytesMethods}; | ||
use crate::{FromPyObject, PyAny, PyErr, PyResult, Python}; | ||
|
||
impl FromPyObject<'_> for Bytes { | ||
fn extract_bound(ob: &Bound<'_, PyAny>) -> PyResult<Self> { | ||
if let Ok(bytes) = ob.downcast::<PyBytes>() { | ||
Ok(Bytes::from((*bytes).as_bytes().to_vec())) | ||
} else if let Ok(bytearray) = ob.downcast::<PyByteArray>() { | ||
Ok(Bytes::from((*bytearray).to_vec())) | ||
} else { | ||
Err(PyTypeError::new_err("expected bytes or bytearray")) | ||
} | ||
} | ||
} | ||
|
||
impl FromPyObject<'_> for BytesMut { | ||
fn extract_bound(ob: &Bound<'_, PyAny>) -> PyResult<Self> { | ||
let bytes = ob.extract::<Bytes>()?; | ||
Ok(BytesMut::from(bytes)) | ||
} | ||
} | ||
|
||
impl<'py> IntoPyObject<'py> for Bytes { | ||
type Target = PyBytes; | ||
type Output = Bound<'py, Self::Target>; | ||
type Error = PyErr; | ||
|
||
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> { | ||
Ok(PyBytes::new(py, &self)) | ||
} | ||
} | ||
|
||
impl<'py> IntoPyObject<'py> for BytesMut { | ||
type Target = PyBytes; | ||
type Output = Bound<'py, Self::Target>; | ||
type Error = PyErr; | ||
|
||
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> { | ||
Ok(PyBytes::new(py, &self)) | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use bytes::{Bytes, BytesMut}; | ||
|
||
use crate::{ | ||
conversion::IntoPyObject, | ||
ffi, | ||
types::{any::PyAnyMethods, PyBytes}, | ||
Python, | ||
}; | ||
|
||
#[test] | ||
fn test_bytes() { | ||
Python::with_gil(|py| { | ||
let py_bytes = py.eval(ffi::c_str!("b'foobar'"), None, None).unwrap(); | ||
let bytes: Bytes = py_bytes.extract().unwrap(); | ||
assert_eq!(bytes, Bytes::from(b"foobar".to_vec())); | ||
|
||
let bytes = Bytes::from(b"foobar".to_vec()).into_pyobject(py).unwrap(); | ||
assert!(bytes.is_instance_of::<PyBytes>()); | ||
}); | ||
} | ||
|
||
#[test] | ||
fn test_bytearray() { | ||
Python::with_gil(|py| { | ||
let py_bytearray = py | ||
.eval(ffi::c_str!("bytearray(b'foobar')"), None, None) | ||
.unwrap(); | ||
let bytes: Bytes = py_bytearray.extract().unwrap(); | ||
assert_eq!(bytes, Bytes::from(b"foobar".to_vec())); | ||
}); | ||
} | ||
|
||
#[test] | ||
fn test_bytes_mut() { | ||
Python::with_gil(|py| { | ||
let py_bytearray = py | ||
.eval(ffi::c_str!("bytearray(b'foobar')"), None, None) | ||
.unwrap(); | ||
let bytes: BytesMut = py_bytearray.extract().unwrap(); | ||
assert_eq!(bytes, BytesMut::from(&b"foobar"[..])); | ||
|
||
let bytesmut = BytesMut::from(&b"foobar"[..]).into_pyobject(py).unwrap(); | ||
assert!(bytesmut.is_instance_of::<PyBytes>()); | ||
}); | ||
} | ||
|
||
#[test] | ||
fn test_bytearray_mut() { | ||
Python::with_gil(|py| { | ||
let py_bytearray = py | ||
.eval(ffi::c_str!("bytearray(b'foobar')"), None, None) | ||
.unwrap(); | ||
let bytes: BytesMut = py_bytearray.extract().unwrap(); | ||
assert_eq!(bytes, BytesMut::from(&b"foobar"[..])); | ||
}); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,6 +2,7 @@ | |
|
||
pub mod anyhow; | ||
pub mod bigdecimal; | ||
pub mod bytes; | ||
pub mod chrono; | ||
pub mod chrono_tz; | ||
pub mod either; | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It would be more efficient to create a
PyBytes
object directly here. This is an example of why I'm not a fan of the Rust to Python conversion.