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

First version of C-API #3327

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
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
Next Next commit
PyObjectPtr: no RC even through function pointers
  • Loading branch information
youknowone committed Oct 16, 2021
commit 317dbd23c6af418432166779073b6eb57a5babd8
46 changes: 43 additions & 3 deletions vm/src/pyobjectrc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 122,8 @@ impl<T> Drop for PyObject<T> {
}
}

type PyObjectRefInner = PyObject<Erased>;

/// The `PyObjectRef` is one of the most used types. It is a reference to a
/// python object. A single python object can have multiple references, and
/// this reference counting is accounted for by this type. Use the `.clone()`
Expand All @@ -130,13 132,13 @@ impl<T> Drop for PyObject<T> {
#[derive(Clone)]
#[repr(transparent)]
pub struct PyObjectRef {
rc: PyRc<PyObject<Erased>>,
rc: PyRc<PyObjectRefInner>,
}

#[derive(Clone)]
#[repr(transparent)]
pub struct PyObjectWeak {
weak: PyWeak<PyObject<Erased>>,
weak: PyWeak<PyObjectRefInner>,
}

pub trait PyObjectWrap
Expand Down Expand Up @@ -175,7 177,7 @@ impl PyObjectRef {

fn new<T: PyObjectPayload>(value: PyObject<T>) -> Self {
let inner = PyRc::into_raw(PyRc::new(value));
let rc = unsafe { PyRc::from_raw(inner as *const PyObject<Erased>) };
let rc = unsafe { PyRc::from_raw(inner as *const PyObjectRefInner) };
Self { rc }
}

Expand Down Expand Up @@ -306,6 308,17 @@ impl PyObjectRef {
None
}
}

#[inline]
pub fn with_ptr<F, R>(&self, f: F) -> R
where
F: FnOnce(PyObjectPtr) -> R,
{
unsafe {
// SAFETY: self will be alive until f is done
f(PyObjectPtr::new(self))
}
}
}

impl AsRef<Self> for PyObjectRef {
Expand Down Expand Up @@ -620,6 633,33 @@ pub(crate) fn init_type_hierarchy() -> (PyTypeRef, PyTypeRef) {
(type_type, object_type)
}

#[derive(Clone, Copy)]
pub struct PyObjectPtr {
obj: *mut PyObjectRefInner,
}

impl PyObjectPtr {
/// # Safety
///
/// `obj` *MUST* be alive until this ptr is destroyed.
/// Do not directly call this function without helper functions.
unsafe fn new(obj: &PyObjectRef) -> Self {
let obj = std::mem::transmute_copy(obj);
Self { obj }
}
}

impl Deref for PyObjectPtr {
type Target = PyObjectRef;

fn deref(&self) -> &Self::Target {
unsafe {
// SAFETY: only when PyObjectRef = PyRc<PyObjectRefInner>
std::mem::transmute(&self.obj)
}
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down