-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Add bytesarray support to the c-api #8009
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
Merged
Merged
Changes from all commits
Commits
Show all changes
2 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,127 @@ | ||
| use crate::PyObject; | ||
| use crate::object::define_py_check; | ||
| use crate::pystate::with_vm; | ||
| use core::ffi::c_char; | ||
| use rustpython_vm::builtins::PyByteArray; | ||
| use rustpython_vm::byte::bytes_from_object; | ||
|
|
||
| define_py_check!(fn PyByteArray_Check, types.bytearray_type); | ||
|
|
||
| /// # Safety | ||
| /// | ||
| /// If `bytes` is `NULL`, the returned bytearray may contain uninitialized | ||
| /// bytes. The caller is responsible for initializing all bytes before any read. | ||
| #[unsafe(no_mangle)] | ||
| #[allow(clippy::uninit_vec)] | ||
| pub unsafe extern "C" fn PyByteArray_FromStringAndSize( | ||
| bytes: *const c_char, | ||
| len: isize, | ||
| ) -> *mut PyObject { | ||
| with_vm(|vm| { | ||
| let len: usize = len.try_into().map_err(|_| { | ||
| vm.new_system_error("Negative size passed to PyByteArray_FromStringAndSize") | ||
| })?; | ||
|
|
||
| let data = if bytes.is_null() { | ||
| let mut data = Vec::with_capacity(len); | ||
| // SAFETY: `bytes == NULL` follows CPython semantics here; caller must | ||
| // initialize all bytes before any read. We keep this behavior for C-API | ||
| // compatibility and to avoid unnecessary zero-initialization overhead. | ||
| unsafe { data.set_len(len) }; | ||
| data | ||
|
bschoenmaeckers marked this conversation as resolved.
|
||
| } else { | ||
| unsafe { core::slice::from_raw_parts(bytes.cast::<u8>(), len) }.to_vec() | ||
| }; | ||
|
bschoenmaeckers marked this conversation as resolved.
|
||
|
|
||
| Ok(vm.ctx.new_bytearray(data)) | ||
| }) | ||
| } | ||
|
|
||
| #[unsafe(no_mangle)] | ||
| pub unsafe extern "C" fn PyByteArray_FromObject(obj: *mut PyObject) -> *mut PyObject { | ||
| with_vm(|vm| { | ||
| let obj = unsafe { &*obj }; | ||
| let data = bytes_from_object(vm, obj)?; | ||
| Ok(vm.ctx.new_bytearray(data)) | ||
| }) | ||
| } | ||
|
|
||
| #[unsafe(no_mangle)] | ||
| pub unsafe extern "C" fn PyByteArray_Size(bytearray: *mut PyObject) -> isize { | ||
| with_vm(|vm| { | ||
| let bytearray = unsafe { &*bytearray }.try_downcast_ref::<PyByteArray>(vm)?; | ||
| Ok(bytearray.borrow_buf().len()) | ||
| }) | ||
| } | ||
|
|
||
| #[unsafe(no_mangle)] | ||
| pub unsafe extern "C" fn PyByteArray_AsString(bytearray: *mut PyObject) -> *mut c_char { | ||
| with_vm(|vm| { | ||
| let bytearray = unsafe { &*bytearray }.try_downcast_ref::<PyByteArray>(vm)?; | ||
| Ok(bytearray.borrow_buf_mut().as_mut_ptr()) | ||
| }) | ||
| } | ||
|
|
||
| #[unsafe(no_mangle)] | ||
| pub unsafe extern "C" fn PyByteArray_Resize(bytearray: *mut PyObject, len: isize) -> i32 { | ||
| with_vm(|vm| { | ||
| let bytearray = unsafe { &*bytearray }.try_downcast_ref::<PyByteArray>(vm)?; | ||
| bytearray.resize(len, vm)?; | ||
| Ok(()) | ||
| }) | ||
| } | ||
|
|
||
| #[cfg(false)] | ||
| mod tests { | ||
| use pyo3::prelude::*; | ||
| use pyo3::types::{PyByteArray, PyBytes}; | ||
|
|
||
| #[test] | ||
| fn bytearray_size() { | ||
| Python::attach(|py| { | ||
| let bytearray = PyByteArray::new(py, b"abc"); | ||
| assert_eq!(bytearray.len(), 3); | ||
| }) | ||
| } | ||
|
|
||
| #[test] | ||
| fn bytearray_resize() { | ||
| Python::attach(|py| { | ||
| let bytearray = PyByteArray::new(py, b"abcde"); | ||
| bytearray.resize(3).unwrap(); | ||
| assert_eq!(bytearray.len(), 3); | ||
| assert_eq!(bytearray.to_vec(), b"abc"); | ||
| }) | ||
| } | ||
|
|
||
| #[test] | ||
| fn bytearray_from_string_and_size() { | ||
| Python::attach(|py| { | ||
| let bytearray = PyByteArray::new(py, b"hello"); | ||
| assert_eq!(bytearray.len(), 5); | ||
| assert_eq!(bytearray.to_vec(), b"hello"); | ||
| }) | ||
| } | ||
|
|
||
| #[test] | ||
| fn bytearray_new_with_zero_initialized() { | ||
| Python::attach(|py| { | ||
| let bytearray = PyByteArray::new_with(py, 4, |bytes| { | ||
| bytes[..2].copy_from_slice(b"hi"); | ||
| Ok(()) | ||
| }) | ||
| .unwrap(); | ||
| assert_eq!(bytearray.len(), 4); | ||
| assert_eq!(bytearray.to_vec(), b"hi\0\0"); | ||
| }) | ||
| } | ||
|
|
||
| #[test] | ||
| fn bytearray_from_object() { | ||
| Python::attach(|py| { | ||
| let source = PyBytes::new(py, b"ABC"); | ||
| let bytearray = PyByteArray::from(&source).unwrap(); | ||
| assert_eq!(bytearray.to_vec(), b"ABC"); | ||
| }) | ||
| } | ||
| } | ||
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
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.
is this safe? to be safe, buffer must be written before read. this code doesn't seem to ensure that.
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.
This is unsafe indeed, but it is the responsibility of the caller to write the data before reading it.
See for example this snipped in PyO3.
https://github.com/PyO3/pyo3/blob/b2163a0916db9fe1baef3bcd3e224531dce508fe/src/types/bytearray.rs#L78-L97
We could also initialise it with zero ourselves, but this writes the data 2 times, which is wasteful in my eyes.
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.
Please add a
# Safetysection to this function about this decision. The section needs to include: