Skip to main content

module_lattice/
maybe_box.rs

1use core::ops::{Deref, DerefMut};
2
3/// `Box`-like type providing opportunistic heap allocation when the `alloc` feature is available
4/// that falls back to stack allocation when it's unavailable.
5#[derive(Clone, Debug, PartialEq)]
6pub struct MaybeBox<T> {
7    #[cfg(not(feature = "alloc"))]
8    inner: T,
9    #[cfg(feature = "alloc")]
10    inner: alloc::boxed::Box<T>,
11}
12
13impl<T> MaybeBox<T> {
14    /// Create a new `MaybeBox`, using `Box` if `alloc` is available.
15    #[inline]
16    pub fn new(inner: T) -> Self {
17        #[cfg(not(feature = "alloc"))]
18        {
19            Self { inner }
20        }
21        #[cfg(feature = "alloc")]
22        Self {
23            inner: alloc::boxed::Box::new(inner),
24        }
25    }
26
27    /// Move the contents out of a [`MaybeBox`].
28    ///
29    /// This emulates the compiler magic that allows moving out of a box with `*my_box`.
30    #[inline]
31    #[must_use]
32    pub fn into_inner(self) -> T {
33        #[cfg(not(feature = "alloc"))]
34        {
35            self.inner
36        }
37        #[cfg(feature = "alloc")]
38        {
39            *self.inner
40        }
41    }
42}
43
44impl<T> Deref for MaybeBox<T> {
45    type Target = T;
46
47    fn deref(&self) -> &Self::Target {
48        &self.inner
49    }
50}
51
52impl<T> DerefMut for MaybeBox<T> {
53    fn deref_mut(&mut self) -> &mut Self::Target {
54        &mut self.inner
55    }
56}