Skip to content
Open
Changes from all 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
27 changes: 9 additions & 18 deletions src/types/capsule.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ impl PyCapsule {
/// let capsule = PyCapsule::new(py, (), None).unwrap(); // Oops! `()` is zero sized!
/// });
/// ```
pub fn new<T: 'static + Send + AssertNotZeroSized>(
pub fn new<T: 'static + Send>(
py: Python<'_>,
value: T,
name: Option<CString>,
Expand All @@ -100,16 +100,13 @@ impl PyCapsule {
///
/// The `destructor` must be `Send`, because there is no guarantee which thread it will eventually
/// be called from.
pub fn new_with_destructor<
T: 'static + Send + AssertNotZeroSized,
F: FnOnce(T, *mut c_void) + Send,
>(
pub fn new_with_destructor<T: 'static + Send, F: FnOnce(T, *mut c_void) + Send>(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it make sense to add a #[track_caller] here (and above) as well, so that the error does not point into pyo3 code?

py: Python<'_>,
value: T,
name: Option<CString>,
destructor: F,
) -> PyResult<Bound<'_, Self>> {
AssertNotZeroSized::assert_not_zero_sized(&value);
const { assert_not_zero_size::<T>() }

// Sanity check for capsule layout
debug_assert_eq!(offset_of!(CapsuleContents::<T, F>, value), 0);
Expand Down Expand Up @@ -565,20 +562,14 @@ unsafe extern "C" fn capsule_destructor<T: 'static + Send, F: FnOnce(T, *mut c_v
}

/// Guarantee `T` is not zero sized at compile time.
// credit: `<https://users.rust-lang.org/t/is-it-possible-to-assert-at-compile-time-that-foo-t-is-not-called-with-a-zst/67685>`
#[doc(hidden)]
pub trait AssertNotZeroSized: Sized {
const _CONDITION: usize = (std::mem::size_of::<Self>() == 0) as usize;
const _CHECK: &'static str =
["PyCapsule value type T must not be zero-sized!"][Self::_CONDITION];
#[allow(path_statements, clippy::no_effect)]
fn assert_not_zero_sized(&self) {
<Self as AssertNotZeroSized>::_CHECK;
}
#[track_caller]
const fn assert_not_zero_size<T>() {
assert!(
size_of::<T>() != 0,
"PyCapsule value type T must not be zero-sized!"
)
}

impl<T> AssertNotZeroSized for T {}

fn ensure_no_error(py: Python<'_>) -> PyResult<()> {
if let Some(err) = PyErr::take(py) {
Err(err)
Expand Down
Loading