PyO3 / PyO3/pyo3

API for returning a memoryview pointing at memory in a Py<T>

Open
#5,871 6 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Rust
Stars
16.2k
Forks
1k
Avg merge
2d 6h
Merged PRs (30d)
66

Description

We've got APIs that give you a memoryview given a Python object that implements the buffer protocol, but not one that gives you a memoryview just given a Py that stores some bytes!

I think it's possible to do this soundly!

As concrete, motivating examples:

These allocates new PyBytes every time they're accessed, doing allocations and copying all those bytes. Sad!

Here's a rough sketch of what I think can work:

impl PyMemoryView {
    pub fn from_owned_buffer<'py, T>(
        py: Python<'py>,
        owner: Py<T>,
        getbuf: impl for<'a> FnOnce(&'a T) -> &'a [u8],
    ) -> PyResult<Bound<'py, Self>>
    where
        T: PyClass<Frozen = True>,
    {
        let data: &T = owner.get();
        let buf: &[u8] = getbuf(data);
        let buf_ptr = buf.as_ptr();
        let buf_len = buf.len();
    
        let obj_ptr = owner.into_ptr();
    
        let mut view: ffi::Py_buffer = unsafe { std::mem::zeroed() };
    
        let rc = unsafe {
            ffi::PyBuffer_FillInfo(
                &mut view,
                obj_ptr,
                buf_ptr as *mut _,
                buf_len as ffi::Py_ssize_t,
                1,                // readonly
                ffi::PyBUF_FULL_RO,
            )
        };
        if rc < 0 {
            unsafe { ffi::Py_DECREF(obj_ptr); }
            return Err(PyErr::fetch(py));
        }
    
        let mv_ptr = unsafe { ffi::PyMemoryView_FromBuffer(&view) };
        if mv_ptr.is_null() {
            // PyMemoryView_FromBuffer calls PyBuffer_Release on failure,
            // which decrefs view.obj — so we do NOT decref again.
            return Err(PyErr::fetch(py));
        }
    
        // PyBuffer_FillInfo already incref'd obj_ptr via view.obj,
        // but we consumed a refcount from into_ptr() that nobody owns
        // now. Decref the extra one.
        unsafe { ffi::Py_DECREF(obj_ptr); }
    
        unsafe {
            Ok(Bound::from_owned_ptr(py, mv_ptr).downcast_into_unchecked())
        }
    }
}

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reviewing PyO3's PyMemoryView APIs and the referenced cryptography files: src/rust/src/x509/certificate.rs and src/rust/src/x509/ocsp_resp.rs. Trace the buffer ownership and reference-count requirements in the proposed API, then verify that the resulting memoryview can point at existing Py storage without repeated allocation or copying.

Written by the indexing model from the issue text.

Assessment

Tech stack
python, rust
Domain
backend-api-design
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.