Skip to content
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

make from_bytes() accept python's buffer API #306

Merged
merged 1 commit into from
Oct 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions chia_py_streamable_macro/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,8 +120,14 @@ pub fn py_streamable_macro(input: proc_macro::TokenStream) -> proc_macro::TokenS
impl #ident {
#[staticmethod]
#[pyo3(name = "from_bytes")]
pub fn py_from_bytes(blob: &[u8]) -> pyo3::PyResult<Self> {
let mut input = std::io::Cursor::<&[u8]>::new(blob);
pub fn py_from_bytes(blob: pyo3::buffer::PyBuffer<u8>) -> pyo3::PyResult<Self> {
arvidn marked this conversation as resolved.
Show resolved Hide resolved
if !blob.is_c_contiguous() {
panic!("from_bytes() must be called with a contiguous buffer");
}
let slice = unsafe {
std::slice::from_raw_parts(blob.buf_ptr() as *const u8, blob.len_bytes())
};
let mut input = std::io::Cursor::<&[u8]>::new(slice);
<Self as #crate_name::Streamable>::parse(&mut input).map_err(|e| <#crate_name::chia_error::Error as Into<pyo3::PyErr>>::into(e))
}

Expand Down
4 changes: 4 additions & 0 deletions tests/test_streamable.py
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,10 @@ def test_program() -> None:
assert str(p) == "Program(ff8080)"
assert p.to_bytes() == bytes.fromhex("ff8080")

# make sure we can pass in a slice/memoryview
p = Program.from_bytes(bytes.fromhex("00ff8080")[1:])
assert str(p) == "Program(ff8080)"

# truncated serialization
with pytest.raises(ValueError, match="unexpected end of buffer"):
Program.from_bytes(bytes.fromhex("ff80"))
Expand Down
Loading