devela/sys/mem/aligned.rs
1// devela::sys::mem::aligned
2//
3//! Defines [`MemAligned`].
4//
5
6#[cfg(doc)]
7use crate::Mem;
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/// For runtime alignment adjustments, see [`Mem::align_down`] and [`Mem::align_up`].
20//
21// WAIT:DONE:1.79 [ptr.is_aligned](https://github.com/rust-lang/rust/pull/121948)
22// WAIT: [pointer_is_aligned_to](https://github.com/rust-lang/rust/issues/96284)
23// WAIT: [const_pointer_is_aligned](https://github.com/rust-lang/rust/issues/104203)
24#[cfg_attr(nightly_doc, doc(notable_trait))]
25#[expect(private_bounds, reason = "Sealed")]
26pub trait MemAligned: Sealed {
27 /// Checks if the `Candidate`'s alignment is compatible with the `Requirement`'s alignment.
28 ///
29 /// Returns `true` if `Candidate` type's alignment is less than or equal to the
30 /// `Requirement` type's alignment.
31 ///
32 /// Alignment represents the byte boundary to which a type must be aligned
33 /// in memory. It is crucial to ensure that types are placed in memory
34 /// locations that respect their alignment requirements.
35 #[must_use]
36 fn is_compatible() -> bool;
37
38 /// Asserts that the memory alignment of the `Candidate` type meets or
39 /// exceeds the `Requirement` type's alignment.
40 ///
41 /// # Panics
42 /// Panics if the `Candidate` type's alignment is greater than the
43 /// `Requirement` type's alignment, indicating an incompatibility that could
44 /// lead to undefined behavior or performance penalties.
45 fn assert_compatibility();
46}
47
48// #[cfg(not(feature = "nightly_const"))]
49impl<Candidate, Requirement> MemAligned for (Candidate, Requirement) {
50 fn is_compatible() -> bool {
51 align_of::<Candidate>() <= align_of::<Requirement>()
52 }
53
54 fn assert_compatibility() {
55 assert!(
56 Self::is_compatible(),
57 "`Candidate`'s alignment ({}) exceeds `Requirement`'s alignment ({}).",
58 align_of::<Candidate>(),
59 align_of::<Requirement>(),
60 );
61 }
62}
63// IMPROVE: compile-time check
64// WAIT: [generic_const_exprs](https://github.com/rust-lang/rust/issues/76560)
65// #[cfg(feature = "nightly_const")]
66// impl<Candidate, Requirement> MemAligned for (Candidate, Requirement)
67// where
68// [(); align_of::<Requirement>() - align_of::<Candidate>()]: Sized,
69// {
70// fn check() {}
71// }