pub unsafe trait ValidAsZeroBits: Copy + 'static { }Expand description
Marker trait for types whose all-zero bit pattern is a valid value.
Crates that allocate GPU memory often use cudaMemset(0) / cuMemsetD8
to initialize buffers to zero and then treat the allocation as a
populated [T]. That’s only sound for types where all-zero bytes are a
valid T — e.g. integer primitives and IEEE-754 floating-point types
(where 0x00000000 is the representation of +0.0).
Implementing ValidAsZeroBits is a promise that:
- Reading a zero-initialized
Tis not undefined behavior. - The zero-initialized value is semantically sensible (
0/0.0/(0, 0, ..., 0)— not a niche-optimized enum where zero means something else).
§Safety
This trait is unsafe to implement: a wrong impl will lead to UB the
first time downstream code zero-initializes a buffer and reads it back.
Common counter-examples include:
&T,&mut T(null references are UB).NonZero*fromstd::num.- Enums with a non-zero discriminant for their zero-value variant.
Box<T>,Arc<T>,String,Vec<T>(heap-owned data).
§Supplied impls
- Every unsigned integer (
u8..u128,usize). - Every signed integer (
i8..i128,isize). f32,f64(zero =+0.0).Half,BFloat16,Complex32,Complex64.()— the unit type.bool— zero =false.- Tuples of arity 1–12 where every element is
ValidAsZeroBits. - Fixed-size arrays
[T; N]whereT: ValidAsZeroBits.
§Example
use baracuda_types::ValidAsZeroBits;
fn zeroed_vec<T: ValidAsZeroBits>(n: usize) -> Vec<T> {
// Safe because T: ValidAsZeroBits guarantees all-zero bytes are a valid T.
let mut v = Vec::with_capacity(n);
unsafe {
core::ptr::write_bytes(v.as_mut_ptr(), 0, n);
v.set_len(n);
}
v
}
let xs: Vec<f32> = zeroed_vec(4);
assert_eq!(xs, [0.0, 0.0, 0.0, 0.0]);Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.