1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// Copyright (c) 2017-present PyO3 Project and Contributors

//! Represent Python Buffer protocol implementation
//!
//! For more information check [buffer protocol](https://docs.python.org/3/c-api/buffer.html)
//! c-api
use crate::callback::UnitCallbackConverter;
use crate::err::PyResult;
use crate::ffi;
use crate::type_object::PyTypeInfo;
use std::os::raw::c_int;

/// Buffer protocol interface
///
/// For more information check [buffer protocol](https://docs.python.org/3/c-api/buffer.html)
/// c-api
#[allow(unused_variables)]
pub trait PyBufferProtocol<'p>: PyTypeInfo {
    fn bf_getbuffer(&'p self, view: *mut ffi::Py_buffer, flags: c_int) -> Self::Result
    where
        Self: PyBufferGetBufferProtocol<'p>,
    {
        unimplemented!()
    }

    fn bf_releasebuffer(&'p self, view: *mut ffi::Py_buffer) -> Self::Result
    where
        Self: PyBufferReleaseBufferProtocol<'p>,
    {
        unimplemented!()
    }
}

pub trait PyBufferGetBufferProtocol<'p>: PyBufferProtocol<'p> {
    type Result: Into<PyResult<()>>;
}

pub trait PyBufferReleaseBufferProtocol<'p>: PyBufferProtocol<'p> {
    type Result: Into<PyResult<()>>;
}

#[doc(hidden)]
pub trait PyBufferProtocolImpl {
    fn tp_as_buffer() -> Option<ffi::PyBufferProcs> {
        None
    }
}

impl<T> PyBufferProtocolImpl for T {}

impl<'p, T> PyBufferProtocolImpl for T
where
    T: PyBufferProtocol<'p>,
{
    #[inline]
    #[allow(clippy::needless_update)] // For python 2 it's not useless
    fn tp_as_buffer() -> Option<ffi::PyBufferProcs> {
        Some(ffi::PyBufferProcs {
            bf_getbuffer: Self::cb_bf_getbuffer(),
            bf_releasebuffer: None,
            ..ffi::PyBufferProcs_INIT
        })
    }
}

trait PyBufferGetBufferProtocolImpl {
    fn cb_bf_getbuffer() -> Option<ffi::getbufferproc> {
        None
    }
}

impl<'p, T> PyBufferGetBufferProtocolImpl for T where T: PyBufferProtocol<'p> {}

impl<T> PyBufferGetBufferProtocolImpl for T
where
    T: for<'p> PyBufferGetBufferProtocol<'p>,
{
    #[inline]
    fn cb_bf_getbuffer() -> Option<ffi::getbufferproc> {
        unsafe extern "C" fn wrap<T>(
            slf: *mut ffi::PyObject,
            arg1: *mut ffi::Py_buffer,
            arg2: c_int,
        ) -> c_int
        where
            T: for<'p> PyBufferGetBufferProtocol<'p>,
        {
            let _pool = crate::GILPool::new();
            let py = crate::Python::assume_gil_acquired();
            let slf = py.mut_from_borrowed_ptr::<T>(slf);

            let result = slf.bf_getbuffer(arg1, arg2).into();
            crate::callback::cb_convert(UnitCallbackConverter, py, result)
        }
        Some(wrap::<T>)
    }
}