devela/sys/mem/aligned.rs
1// devela::sys::mem::aligned
2//
3//! Defines [`MemAligned`].
4//
5//
6// TODO
7// - new struct wrapper Align<>, const generic.?
8
9/// Marker trait to prevent downstream implementations of the [`MemAligned`] trait.
10trait Sealed {}
11impl<Candidate, Requirement> Sealed for (Candidate, Requirement) {}
12
13/// Marker trait to verify memory alignment between two types.
14///
15/// This trait ensures that a value of the `Candidate` type can be safely placed
16/// into a storage medium designed for the `Requirement` type, adhering to
17/// alignment requirements.
18//
19// WAIT:DONE:1.79 [ptr.is_aligned](https://github.com/rust-lang/rust/pull/121948)
20// WAIT: [pointer_is_aligned_to](https://github.com/rust-lang/rust/issues/96284)
21// WAIT: [const_pointer_is_aligned](https://github.com/rust-lang/rust/issues/104203)
22#[cfg_attr(feature = "nightly_doc", doc(notable_trait))]
23#[expect(private_bounds, reason = "Sealed")]
24pub trait MemAligned: Sealed {
25 /// Checks if the `Candidate`'s alignment is compatible with the `Requirement`'s alignment.
26 ///
27 /// Returns `true` if `Candidate` type's alignment is less than or equal to the
28 /// `Requirement` type's alignment.
29 ///
30 /// Alignment represents the byte boundary to which a type must be aligned
31 /// in memory. It is crucial to ensure that types are placed in memory
32 /// locations that respect their alignment requirements.
33 #[must_use]
34 fn is_compatible() -> bool;
35
36 /// Asserts that the memory alignment of the `Candidate` type meets or
37 /// exceeds the `Requirement` type's alignment.
38 ///
39 /// # Panics
40 /// Panics if the `Candidate` type's alignment is greater than the
41 /// `Requirement` type's alignment, indicating an incompatibility that could
42 /// lead to undefined behavior or performance penalties.
43 fn assert_compatibility();
44}
45
46// #[cfg(not(feature = "nightly_const"))]
47impl<Candidate, Requirement> MemAligned for (Candidate, Requirement) {
48 fn is_compatible() -> bool {
49 align_of::<Candidate>() <= align_of::<Requirement>()
50 }
51
52 fn assert_compatibility() {
53 assert!(
54 Self::is_compatible(),
55 "`Candidate`'s alignment ({}) exceeds `Requirement`'s alignment ({}).",
56 align_of::<Candidate>(),
57 align_of::<Requirement>(),
58 );
59 }
60}
61// IMPROVE: compile-time check
62// WAIT: [generic_const_exprs](https://github.com/rust-lang/rust/issues/76560)
63// #[cfg(feature = "nightly_const")]
64// impl<Candidate, Requirement> MemAligned for (Candidate, Requirement)
65// where
66// [(); align_of::<Requirement>() - align_of::<Candidate>()]: Sized,
67// {
68// fn check() {}
69// }