devela/sys/mem/storage/mod.rs
1// devela::sys::mem::storage
2//
3//! The [`Storage`] trait allows the data structure implementations to have
4//! specialized methods by storage type (specially useful for constructors).
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(feature = "nightly_doc", doc(cfg(feature = "alloc")))]
18 mod boxed;
19 pub use boxed::*;
20}
21pub use bare::*;
22
23/// Allows to be generic in respect of the data storage.
24///
25/// There are two reference implementations:
26/// - [`Bare`], which wraps the data in a [`BareBox`].
27/// - [`Boxed`], which wraps the data in a [`Box`].
28///
29/// # Examples
30/// ```
31/// use core::array::from_fn;
32/// use devela::Storage;
33///
34/// /// Generically store a generic array of generic size.
35/// pub struct MyStructure<T, S: Storage, const L: usize> {
36/// data: S::Stored<[T; L]>,
37/// }
38///
39/// impl<T: Default, S: Storage, const L: usize> MyStructure<T, S, L> {
40/// pub fn new() -> Self {
41/// Self {
42/// data: S::Stored::from(from_fn(|_| T::default())),
43/// }
44/// }
45/// }
46///
47/// // The array is stored in the stack
48/// assert_eq![100, size_of::<MyStructure::<u8, (), 100>>()];
49///
50/// // The array is stored in the heap.
51/// #[cfg(feature = "alloc")]
52/// assert_eq![8, size_of::<MyStructure::<u8, devela::Boxed, 100>>()];
53///
54/// ```
55pub trait Storage {
56 /// The stored associated type.
57 ///
58 /// Any type `T` that is to be stored must be able to be dereferenced to a
59 /// mutable reference of `T` and to be constructed from a value of type `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}