devela/sys/mem/alloc/storage/mod.rs
1// devela/src/sys/mem/alloc/storage/mod.rs
2//
3//! The [`Storage`] trait allows data structures to abstract over how data is stored,
4//! enabling specialization by storage strategy (e.g. stack vs heap).
5//!
6//! It is already implemented for the [`Bare`] and [`Boxed`] type markers,
7//! which wraps their data in a [`BareBox`] and a [`Box`], respectively.
8//
9
10#[cfg(all(doc, feature = "alloc"))]
11use crate::Box;
12use crate::DerefMut;
13
14mod bare;
15#[cfg(feature = "alloc")]
16crate::items! {
17 #[cfg_attr(nightly_doc, doc(cfg(feature = "alloc")))]
18 mod boxed;
19 pub use boxed::*;
20}
21pub use bare::*;
22
23#[doc = crate::_tags!(mem)]
24/// Allows data structures to be generic over their storage strategy.
25#[doc = crate::_doc_meta!{location("sys/mem/alloc")}]
26///
27/// There are two reference implementations:
28/// - [`Bare`], storing data inline via [`BareBox`].
29/// - [`Boxed`], storing data on the heap via [`Box`].
30///
31/// # Examples
32/// ```
33/// use core::array::from_fn;
34/// use devela::Storage;
35///
36/// /// Generically store a generic array of generic size.
37/// pub struct MyStructure<T, S: Storage, const L: usize> {
38/// data: S::Stored<[T; L]>,
39/// }
40///
41/// impl<T: Default, S: Storage, const L: usize> MyStructure<T, S, L> {
42/// pub fn new() -> Self {
43/// Self {
44/// data: S::Stored::from(from_fn(|_| T::default())),
45/// }
46/// }
47/// }
48///
49/// // The array is stored inline (stack-allocated).
50/// assert_eq![100, size_of::<MyStructure::<u8, (), 100>>()];
51///
52/// // The array is stored in the heap.
53/// #[cfg(feature = "alloc")]
54/// assert_eq![8, size_of::<MyStructure::<u8, devela::Boxed, 100>>()];
55/// ```
56pub trait Storage {
57 /// The stored associated type.
58 ///
59 /// Any stored type must support mutable dereferencing and construction from `T`.
60 type Stored<T>: DerefMut<Target = T> + From<T>;
61
62 /// Returns the static name of the storage implementation.
63 ///
64 /// This can be useful for debugging.
65 fn name() -> &'static str;
66
67 // WAIT: [box_into_inner](https://github.com/rust-lang/rust/issues/80437)
68 // fn unstore(self) -> T;
69}