GeezerVison is showing github.com — Add memoryview support to c-api · RustPython/RustPython@b5be40e
File tree
Expand file treeCollapse file tree
Open diff view settings
Expand file treeCollapse file tree
Open diff view settings
Collapse file
Copy file name to clipboardExpand all lines: crates/capi/src/lib.rs +1Lines changed: 1 addition & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -22,6 +22,7 @@ pub mod genericaliasobject; |
22 | 22 | pub mod import; |
23 | 23 | pub mod listobject; |
24 | 24 | pub mod longobject; |
| 25 | +pub mod memoryobject; |
25 | 26 | pub mod methodobject; |
26 | 27 | pub mod moduleobject; |
27 | 28 | pub mod object; |
|
Collapse file
Copy file name to clipboard +37Lines changed: 37 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
|
| 1 | +use crate::object::define_py_check; |
| 2 | +use crate::{PyObject, pystate::with_vm}; |
| 3 | +use rustpython_vm::PyPayload; |
| 4 | +use rustpython_vm::builtins::PyMemoryView; |
| 5 | + |
| 6 | +define_py_check!(fn PyMemoryView_Check, types.memoryview_type); |
| 7 | + |
| 8 | +#[unsafe(no_mangle)] |
| 9 | +pub unsafe extern "C" fn PyMemoryView_FromObject(obj: *mut PyObject) -> *mut PyObject { |
| 10 | + with_vm(|vm| { |
| 11 | + let obj = unsafe { &*obj }; |
| 12 | + Ok(PyMemoryView::from_object(obj, vm)?.into_ref(&vm.ctx)) |
| 13 | + }) |
| 14 | +} |
| 15 | + |
| 16 | +#[cfg(test)] |
| 17 | +mod tests { |
| 18 | + use pyo3::prelude::*; |
| 19 | + use pyo3::types::{PyBytes, PyMemoryView}; |
| 20 | + |
| 21 | + #[test] |
| 22 | + fn memoryview_from_bytes() { |
| 23 | + Python::attach(|py| { |
| 24 | + let bytes = PyBytes::new(py, b"hello"); |
| 25 | + let view = PyMemoryView::from(&bytes).unwrap(); |
| 26 | + |
| 27 | + assert!(view.is_instance_of::<PyMemoryView>()); |
| 28 | + |
| 29 | + let copied = view |
| 30 | + .call_method1("tobytes", ()) |
| 31 | + .unwrap() |
| 32 | + .cast_into::<PyBytes>() |
| 33 | + .unwrap(); |
| 34 | + assert_eq!(copied.as_bytes(), b"hello"); |
| 35 | + }) |
| 36 | + } |
| 37 | +} |