baracuda_types/kernel_arg.rs
1//! The `KernelArg` trait: a uniform way to hand values to
2//! `cuLaunchKernel` / `cudaLaunchKernel`, which expect `void**` — an array
3//! of pointers to each argument.
4//!
5//! Implementors must be [`crate::DeviceRepr`] so we know the layout is
6//! ABI-stable, and must produce a pointer whose pointee will remain valid
7//! for the duration of the kernel launch.
8
9use core::ffi::c_void;
10
11use crate::device_repr::DeviceRepr;
12
13/// A value that can be marshalled into the `void** kernelParams` slot of
14/// `cuLaunchKernel` / `cudaLaunchKernel`.
15///
16/// # Safety
17///
18/// Implementors must uphold:
19///
20/// 1. [`Self::as_kernel_arg_ptr`] returns a pointer whose pointee is a valid
21/// `DeviceRepr` value of the correct type for the target kernel slot.
22/// 2. The returned pointer remains valid until the kernel launch has been
23/// submitted to the stream (not necessarily completed — the runtime
24/// copies argument bytes during submission).
25/// 3. Concurrent kernel launches using the same argument value must tolerate
26/// shared access; in practice this means the referent is either `Copy`
27/// or borrowed immutably for the duration of submission.
28pub unsafe trait KernelArg {
29 fn as_kernel_arg_ptr(&self) -> *mut c_void;
30}
31
32// SAFETY: &T where T: DeviceRepr points to a valid, ABI-stable value.
33// The launch API reads argument bytes during submission, so an immutable
34// borrow for the duration of `launch()` is enough.
35unsafe impl<T: DeviceRepr> KernelArg for &T {
36 #[inline]
37 fn as_kernel_arg_ptr(&self) -> *mut c_void {
38 *self as *const T as *mut c_void
39 }
40}
41
42// SAFETY: same as above; &mut grants even stricter exclusive access.
43unsafe impl<T: DeviceRepr> KernelArg for &mut T {
44 #[inline]
45 fn as_kernel_arg_ptr(&self) -> *mut c_void {
46 *self as *const T as *mut c_void
47 }
48}