Skip to content

Improved closure constructors #5692

@davidhewitt

Description

@davidhewitt

Somewhat inspired by the work going on in #5689.

The current capsule constructors PyCapsule::new and PyCapsule::new_with_destructor have some downsides:

  • They unconditionally allocate the CapsuleContents type.
  • They require an allocated CString for the name, if set (the full name type is Option<CString>)

After we started reworking the capsule methods in 0.27 to require checking a name, I think it would make sense to have a name be required as &'static CStr, to further encourage name checking. Also, if we no longer need to store a CString within the CapsuleContents, for the case of a trivial destructor we don't need to have CapusleContents at all (the only thing to store is T).

This would allow us to store the value as Box<T>, or maybe even store the value without boxing as long as T is no more than pointer sized.

While some experimentation to be had, I'd propose we introduce new constructors for now as

impl PyCapsule {
    pub fn new_with_name<T: 'static + Send + AssertNotZeroSized>(
        py: Python<'_>,
        value: T,
        name: &'static CStr,
    ) -> PyResult<Bound<'_, Self>>;

    pub fn new_with_name_and_destructor<
        T: 'static + Send + AssertNotZeroSized,
        F: FnOnce(T, *mut c_void) + Send,
    >(
        py: Python<'py>,
        value: T,
        name: &'static CStr,
        destructor: F,
    ) -> PyResult<Bound<'_, Self>>;

... and maybe deprecate the existing constructors.

cc @lmmx

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions