rstsr_dtype_traits/
val_write.rs

1use std::mem::MaybeUninit;
2
3/// Sets the value of the current object to `val`.
4///
5/// This trait function is designed for unifying `T` and `MaybeUninit<T>` for
6/// our purposes.
7///
8/// Note that for `MaybeUninit<T>`, if `T` is a type with non trivial `Drop`,
9/// then memory could leak for using this function.
10pub trait ValWriteAPI<T> {
11    fn write(&mut self, val: T) -> &mut T;
12}
13
14impl<T> ValWriteAPI<T> for T {
15    #[inline(always)]
16    fn write(&mut self, val: T) -> &mut T {
17        *self = val;
18        self
19    }
20}
21
22impl<T> ValWriteAPI<T> for MaybeUninit<T> {
23    #[inline(always)]
24    fn write(&mut self, val: T) -> &mut T {
25        self.write(val)
26    }
27}
28
29#[test]
30fn playground() {
31    fn inner<W, T>(a: &mut W, b: T)
32    where
33        W: ValWriteAPI<T>,
34    {
35        a.write(b);
36    }
37
38    let mut a = 0.0;
39    inner(&mut a, 1.0);
40    println!("a {a:?}");
41
42    let mut b = MaybeUninit::uninit();
43    inner(&mut b, 1.0);
44    println!("b {b:?}");
45}