Skip to main content

rs_matter_utils/
init.rs

1/*
2 *
3 *    Copyright (c) 2024-2026 Project CHIP Authors
4 *
5 *    Licensed under the Apache License, Version 2.0 (the "License");
6 *    you may not use this file except in compliance with the License.
7 *    You may obtain a copy of the License at
8 *
9 *        http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *    Unless required by applicable law or agreed to in writing, software
12 *    distributed under the License is distributed on an "AS IS" BASIS,
13 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *    See the License for the specific language governing permissions and
15 *    limitations under the License.
16 */
17
18use core::convert::Infallible;
19use core::{cell::UnsafeCell, mem::MaybeUninit};
20
21/// Re-export `pinned-init` because its API is very unstable currently (0.0.x)
22pub use pinned_init::*;
23// `pinned_init::zeroed` returns a value since 0.0.10; the in-place initializer is `init_zeroed`
24pub use pinned_init::init_zeroed as zeroed;
25
26/// Convert a closure returning `Result<impl Init<T, E>, E>` into an `Init<T, E>`.
27pub fn into_init<F, T, E, I: Init<T, E>>(f: F) -> impl Init<T, E>
28where
29    F: FnOnce() -> Result<I, E>,
30{
31    unsafe { init_from_closure(move |slot| f()?.__init(slot)) }
32}
33
34/// An extension trait for converting `Init<T, Infallible>` to a fallible `Init<T, E>`.
35/// Useful when chaining an infallible initializer with a fallible chained initialization function.
36pub trait IntoFallibleInit<T>: Init<T, Infallible> {
37    /// Convert the infallible initializer to a fallible one.
38    fn into_fallible<E>(self) -> impl Init<T, E> {
39        unsafe {
40            init_from_closure(move |slot| {
41                unwrap!(Self::__init(self, slot));
42
43                Ok(())
44            })
45        }
46    }
47}
48
49impl<T, I> IntoFallibleInit<T> for I where I: Init<T, Infallible> {}
50
51/// An extension trait for retrofitting `UnsafeCell` with an initializer.
52pub trait UnsafeCellInit<T> {
53    /// Create a new in-place initializer for `UnsafeCell`
54    /// by using the given initializer for the value.
55    fn init<I: Init<T>>(value: I) -> impl Init<Self>;
56}
57
58impl<T> UnsafeCellInit<T> for UnsafeCell<T> {
59    fn init<I: Init<T>>(value: I) -> impl Init<Self> {
60        unsafe {
61            init_from_closure::<_, Infallible>(move |slot: *mut Self| {
62                // `slot` contains uninit memory, avoid creating a reference.
63                let slot: *mut T = slot as _;
64
65                // Initialize the value
66                unwrap!(value.__init(slot));
67
68                Ok(())
69            })
70        }
71    }
72}
73
74/// An extension trait that allows safe initialization of
75/// `MaybeUninit<T>` memory.
76pub trait InitMaybeUninit<T> {
77    /// Initialize Self with the given in-place initializer.
78    fn init_with<I: Init<T>>(&mut self, init: I) -> &mut T {
79        unwrap!(self.try_init_with(init))
80    }
81
82    /// Try to initialize Self with the given fallible in-place initializer.
83    fn try_init_with<I: Init<T, E>, E>(&mut self, init: I) -> Result<&mut T, E>;
84
85    /// Initialize Self with all-zeroes
86    fn init_zeroed(&mut self) -> &mut T
87    where
88        T: Zeroable,
89    {
90        self.init_with(pinned_init::init_zeroed())
91    }
92}
93
94impl<T> InitMaybeUninit<T> for MaybeUninit<T> {
95    fn try_init_with<I: Init<T, E>, E>(&mut self, init: I) -> Result<&mut T, E> {
96        unsafe {
97            Init::<T, E>::__init(init, self.as_mut_ptr())?;
98
99            Ok(self.assume_init_mut())
100        }
101    }
102}
103
104/// A trait for types that have a canonical, stack-safe, in-place default initializer.
105///
106/// This is the in-place initialization analogue of `Default`: unlike `Default::default()`
107/// which returns `Self` by value (potentially materializing a large value on the stack),
108/// `init_default()` returns an `Init<Self>` that writes the value directly into its
109/// final memory location. This is essential for large types (e.g. buffers sized in MiB)
110/// whose on-stack construction would overflow the stack.
111pub trait InitDefault: Sized {
112    /// Returns a canonical in-place initializer for `Self`.
113    fn init_default() -> impl Init<Self>;
114}
115
116#[cfg(test)]
117#[cfg_attr(coverage_nightly, coverage(off))]
118mod tests {
119    use core::cell::{Cell, UnsafeCell};
120    use core::mem::MaybeUninit;
121
122    use super::{into_init, Init, InitMaybeUninit, IntoFallibleInit, UnsafeCellInit};
123
124    struct Droppable<'a>(&'a Cell<u32>);
125
126    impl Drop for Droppable<'_> {
127        fn drop(&mut self) {
128            self.0.set(self.0.get() + 1);
129        }
130    }
131
132    #[test]
133    fn maybe_uninit_init_with() {
134        let drops = Cell::new(0);
135
136        let mut slot = MaybeUninit::<Droppable>::uninit();
137        let d = slot.init_with(Droppable(&drops));
138        assert_eq!(d.0.get(), 0);
139
140        // SAFETY: `slot` was initialized by `init_with` above
141        unsafe { slot.assume_init_drop() };
142        assert_eq!(drops.get(), 1);
143
144        let mut slot = MaybeUninit::<u32>::uninit();
145        assert_eq!(*slot.init_zeroed(), 0);
146        assert_eq!(*slot.init_with(7), 7);
147    }
148
149    #[test]
150    fn into_init_and_into_fallible() {
151        let drops = Cell::new(0);
152
153        let mut slot = MaybeUninit::<Droppable>::uninit();
154
155        // A failing initializer reports the error and constructs nothing
156        let r = slot.try_init_with(into_init(|| {
157            Err::<Droppable, i32>(3).map(|d| d.into_fallible())
158        }));
159        assert_eq!(r.err(), Some(3));
160        assert_eq!(drops.get(), 0);
161
162        let r = slot.try_init_with(into_init(|| {
163            Ok::<_, i32>(Droppable(&drops).into_fallible())
164        }));
165        assert!(r.is_ok());
166
167        // SAFETY: `slot` was initialized by `try_init_with` above
168        unsafe { slot.assume_init_drop() };
169        assert_eq!(drops.get(), 1);
170
171        // An unused initializer drops the value it wraps
172        let init = Droppable(&drops).into_fallible::<i32>();
173        drop(init);
174        assert_eq!(drops.get(), 2);
175    }
176
177    #[test]
178    fn unsafe_cell_init() {
179        let mut slot = MaybeUninit::<UnsafeCell<u32>>::uninit();
180        let cell = slot.init_with(UnsafeCell::init(42u32));
181        assert_eq!(*cell.get_mut(), 42);
182    }
183
184    #[test]
185    fn value_is_an_initializer() {
186        fn init<T>(init: impl Init<T>) -> T {
187            let mut slot = MaybeUninit::uninit();
188            slot.init_with(init);
189
190            // SAFETY: `slot` was initialized by `init_with` above
191            unsafe { slot.assume_init() }
192        }
193
194        assert_eq!(init(5u8), 5);
195    }
196}