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

Add PyMemoryView type #3514

Merged
merged 4 commits into from
Oct 15, 2023
Merged
Show file tree
Hide file tree
Changes from 2 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
1 change: 1 addition & 0 deletions newsfragments/3514.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add `PyMemoryView` type.
7 changes: 6 additions & 1 deletion pyo3-ffi/src/memoryobject.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use crate::object::*;
use crate::pyport::Py_ssize_t;
#[cfg(Py_3_11)]
use crate::Py_buffer;
use std::os::raw::{c_char, c_int};
use std::ptr::addr_of_mut;

Expand Down Expand Up @@ -29,7 +31,10 @@ extern "C" {
size: Py_ssize_t,
flags: c_int,
) -> *mut PyObject;
// skipped non-limited PyMemoryView_FromBuffer
#[cfg(Py_3_11)]
#[cfg_attr(PyPy, link_name = "PyPyMemoryView_FromBuffer")]
pub fn PyMemoryView_FromBuffer(view: *const Py_buffer) -> *mut PyObject;
#[cfg_attr(PyPy, link_name = "PyPyMemoryView_GetContiguous")]
pub fn PyMemoryView_GetContiguous(
base: *mut PyObject,
buffertype: c_int,
Expand Down
10 changes: 9 additions & 1 deletion pytests/src/buf_and_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
//! Objects related to PyBuffer and PyStr
use pyo3::buffer::PyBuffer;
use pyo3::prelude::*;
use pyo3::types::{PyBytes, PyString};
use pyo3::types::{PyBytes, PyMemoryView, PyString};

/// This is for confirming that PyBuffer does not cause memory leak
#[pyclass]
Expand Down Expand Up @@ -41,8 +41,16 @@ impl BytesExtractor {
}
}

#[pyfunction]
fn return_memoryview(py: Python<'_>) -> PyResult<&PyMemoryView> {
let bytes = PyBytes::new(py, b"hello world");
let memoryview = PyMemoryView::from(bytes)?;
Ok(memoryview)
}

#[pymodule]
pub fn buf_and_str(_py: Python<'_>, m: &PyModule) -> PyResult<()> {
m.add_class::<BytesExtractor>()?;
m.add_function(wrap_pyfunction!(return_memoryview, m)?)?;
Ok(())
}
9 changes: 8 additions & 1 deletion pytests/tests/test_buf_and_str.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from pyo3_pytests.buf_and_str import BytesExtractor
from pyo3_pytests.buf_and_str import BytesExtractor, return_memoryview


def test_extract_bytes():
Expand Down Expand Up @@ -27,3 +27,10 @@ def test_extract_buffer():

arr = bytearray(b'\\(-"-;) A message written in bytes')
assert extractor.from_buffer(arr) == len(arr)


def test_return_memoryview():
view = return_memoryview()
assert view.readonly
assert view.contiguous
assert view.tobytes() == b"hello world"
10 changes: 10 additions & 0 deletions src/types/bytearray.rs
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,16 @@ impl PyByteArray {
}
}

impl<'py> TryFrom<&'py PyAny> for &'py PyByteArray {
type Error = crate::PyErr;

/// Creates a new Python `bytearray` object from another Python object that
/// implements the buffer protocol.
fn try_from(value: &'py PyAny) -> Result<Self, Self::Error> {
PyByteArray::from(value)
}
}

#[cfg(test)]
mod tests {
use crate::exceptions;
Expand Down
29 changes: 29 additions & 0 deletions src/types/memoryview.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
use crate::err::PyResult;
use crate::{ffi, AsPyPointer, PyAny};

/// Represents a Python `memoryview`.
#[repr(transparent)]
pub struct PyMemoryView(PyAny);

pyobject_native_type_core!(PyMemoryView, pyobject_native_static_type_object!(ffi::PyMemoryView_Type), #checkfunction=ffi::PyMemoryView_Check);

impl PyMemoryView {
/// Creates a new Python `memoryview` object from another Python object that
/// implements the buffer protocol.
pub fn from(src: &PyAny) -> PyResult<&PyMemoryView> {
adamreichold marked this conversation as resolved.
Show resolved Hide resolved
unsafe {
src.py()
.from_owned_ptr_or_err(ffi::PyMemoryView_FromObject(src.as_ptr()))
}
}
}

impl<'py> TryFrom<&'py PyAny> for &'py PyMemoryView {
type Error = crate::PyErr;

/// Creates a new Python `memoryview` object from another Python object that
/// implements the buffer protocol.
fn try_from(value: &'py PyAny) -> Result<Self, Self::Error> {
PyMemoryView::from(value)
}
}
2 changes: 2 additions & 0 deletions src/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ pub use self::function::PyFunction;
pub use self::iterator::PyIterator;
pub use self::list::PyList;
pub use self::mapping::PyMapping;
pub use self::memoryview::PyMemoryView;
pub use self::module::PyModule;
pub use self::none::PyNone;
pub use self::notimplemented::PyNotImplemented;
Expand Down Expand Up @@ -289,6 +290,7 @@ mod function;
mod iterator;
pub(crate) mod list;
mod mapping;
mod memoryview;
mod module;
mod none;
mod notimplemented;
Expand Down
Loading