Skip to main content

c_support/memory/
layout.rs

1use core::{alloc::Layout, fmt::Debug};
2
3use memory::CapabilityFlags;
4
5#[repr(transparent)]
6#[derive(Clone, Copy, PartialEq, Eq)]
7pub struct CompactLayout(usize);
8
9impl Debug for CompactLayout {
10    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
11        write!(
12            f,
13            "CompactLayout {{ size: {}, alignment: {}, capabilities: {:?} }}",
14            self.get_size(),
15            self.get_alignment(),
16            self.get_capabilities()
17        )
18    }
19}
20
21impl CompactLayout {
22    /// Alignment is stored in the upper 4 bits in a log2 format
23    const ALIGNMENT_BITS: u8 = 4;
24    /// Capability flags occupy the next three bits, leaving the low bits for size.
25    const CAPABILITY_BITS: u8 = 3;
26    const SIZE_BITS: u8 = usize::BITS as u8 - Self::ALIGNMENT_BITS - Self::CAPABILITY_BITS;
27    const CAPABILITY_SHIFT: u8 = Self::SIZE_BITS;
28    const ALIGNMENT_SHIFT: u8 = Self::SIZE_BITS + Self::CAPABILITY_BITS;
29    const CAPABILITY_MASK: u8 = (1 << Self::CAPABILITY_BITS) - 1;
30
31    pub(super) const MAXIMUM_SIZE: usize = (1 << Self::SIZE_BITS) - 1;
32
33    // A new capability flag must widen the field, or blocks that carry it
34    // would be allocated and then lose their metadata.
35    const _CAPABILITIES_FIT: () =
36        assert!(CapabilityFlags::all().bits() as usize <= Self::CAPABILITY_MASK as usize);
37    pub(super) const MAXIMUM_ALIGNMENT: usize = 1 << ((1 << Self::ALIGNMENT_BITS) - 1);
38
39    pub const fn from_layout(layout: &Layout, capabilities: CapabilityFlags) -> Option<Self> {
40        let size = layout.size();
41        let alignment = layout.align();
42
43        if size > Self::MAXIMUM_SIZE
44            || alignment > Self::MAXIMUM_ALIGNMENT
45            || capabilities.bits() > Self::CAPABILITY_MASK
46        {
47            return None;
48        }
49
50        let alignment_log2 = alignment.ilog2() as usize;
51
52        let compacted = size
53            | ((capabilities.bits() as usize) << Self::CAPABILITY_SHIFT)
54            | (alignment_log2 << Self::ALIGNMENT_SHIFT);
55        Some(Self(compacted))
56    }
57
58    pub const fn into_layout(&self) -> Option<Layout> {
59        let size = self.get_size();
60        let alignment = self.get_alignment();
61
62        match Layout::from_size_align(size, alignment) {
63            Ok(layout) => Some(layout),
64            Err(_) => None,
65        }
66    }
67
68    pub const fn get_size(&self) -> usize {
69        self.0 & Self::MAXIMUM_SIZE
70    }
71
72    pub const fn get_alignment_log2(&self) -> usize {
73        (self.0 >> Self::ALIGNMENT_SHIFT) & ((1 << Self::ALIGNMENT_BITS) - 1)
74    }
75
76    pub const fn get_alignment(&self) -> usize {
77        1 << self.get_alignment_log2()
78    }
79
80    pub const fn to_le_bytes(&self) -> [u8; size_of::<Self>()] {
81        self.0.to_le_bytes()
82    }
83
84    pub const fn get_capabilities(&self) -> CapabilityFlags {
85        let bits = (self.0 >> Self::CAPABILITY_SHIFT) as u8 & Self::CAPABILITY_MASK;
86        CapabilityFlags::from_bits_retain(bits)
87    }
88
89    pub const fn from_le_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
90        Self(usize::from_le_bytes(bytes))
91    }
92}
93
94// 32-bit targets keep 25 size bits, so a block is at most 32 MiB - 1, and one
95// byte more is rejected rather than spilling into the capability bits.
96// Checked at compile time so the bare-metal CI build enforces it.
97#[cfg(target_pointer_width = "32")]
98const _: () = {
99    assert!(CompactLayout::MAXIMUM_SIZE == (1 << 25) - 1);
100    let Ok(too_large) = Layout::from_size_align(CompactLayout::MAXIMUM_SIZE + 1, 8) else {
101        panic!("invalid probe layout");
102    };
103    assert!(CompactLayout::from_layout(&too_large, CapabilityFlags::all()).is_none());
104};
105
106#[cfg(test)]
107mod tests {
108    use super::*;
109
110    #[test]
111    fn test_basic_layout_conversion() {
112        let layout = Layout::from_size_align(64, 8).unwrap();
113        let compact = CompactLayout::from_layout(&layout, CapabilityFlags::empty()).unwrap();
114        let restored = compact.into_layout().unwrap();
115        assert_eq!(restored, layout);
116    }
117
118    #[test]
119    fn test_minimum_size() {
120        let layout = Layout::from_size_align(0, 1).unwrap();
121        let compact = CompactLayout::from_layout(&layout, CapabilityFlags::empty()).unwrap();
122        assert_eq!(compact.get_size(), 0);
123    }
124
125    #[test]
126    fn test_maximum_size() {
127        let layout = Layout::from_size_align(CompactLayout::MAXIMUM_SIZE, 1).unwrap();
128        let compact = CompactLayout::from_layout(&layout, CapabilityFlags::empty()).unwrap();
129        assert_eq!(compact.get_size(), CompactLayout::MAXIMUM_SIZE);
130    }
131
132    // 32-bit targets keep 25 size bits: a block is at most 32 MiB - 1.
133    #[cfg(target_pointer_width = "32")]
134    #[test]
135    fn test_32_bit_packing() {
136        assert_eq!(CompactLayout::MAXIMUM_SIZE, (1 << 25) - 1);
137        let layout = Layout::from_size_align(CompactLayout::MAXIMUM_SIZE, 8).unwrap();
138        let compact = CompactLayout::from_layout(&layout, CapabilityFlags::all()).unwrap();
139        assert_eq!(compact.get_size(), CompactLayout::MAXIMUM_SIZE);
140        assert_eq!(compact.get_capabilities(), CapabilityFlags::all());
141        assert_eq!(compact.get_alignment(), 8);
142        let too_large = Layout::from_size_align(CompactLayout::MAXIMUM_SIZE + 1, 8).unwrap();
143        assert!(CompactLayout::from_layout(&too_large, CapabilityFlags::all()).is_none());
144    }
145
146    #[test]
147    fn test_size_overflow() {
148        let layout = Layout::from_size_align(CompactLayout::MAXIMUM_SIZE + 1, 1).unwrap();
149        assert!(CompactLayout::from_layout(&layout, CapabilityFlags::empty()).is_none());
150    }
151
152    #[test]
153    fn test_minimum_alignment() {
154        let layout = Layout::from_size_align(8, 1).unwrap();
155        let compact = CompactLayout::from_layout(&layout, CapabilityFlags::empty()).unwrap();
156        assert_eq!(compact.get_alignment(), 1);
157    }
158
159    #[test]
160    fn test_maximum_alignment() {
161        let layout = Layout::from_size_align(8, CompactLayout::MAXIMUM_ALIGNMENT).unwrap();
162        let compact = CompactLayout::from_layout(&layout, CapabilityFlags::empty()).unwrap();
163        assert_eq!(compact.get_alignment(), CompactLayout::MAXIMUM_ALIGNMENT);
164    }
165
166    #[test]
167    fn test_alignment_overflow() {
168        let layout = Layout::from_size_align(8, CompactLayout::MAXIMUM_ALIGNMENT * 2).unwrap();
169        assert!(CompactLayout::from_layout(&layout, CapabilityFlags::empty()).is_none());
170    }
171
172    #[test]
173    fn test_non_power_of_two_alignment() {
174        // Layout::from_size_align already validates power of two, so we can't directly test
175        // but we verify the check is in place
176        let layout = Layout::from_size_align(16, 8).unwrap();
177        assert!(CompactLayout::from_layout(&layout, CapabilityFlags::empty()).is_some());
178    }
179
180    #[test]
181    fn test_various_alignments() {
182        for exp in 0..=(CompactLayout::ALIGNMENT_BITS as u32 * 2) {
183            let align = 1 << exp;
184            if align <= CompactLayout::MAXIMUM_ALIGNMENT {
185                let layout = Layout::from_size_align(16, align).unwrap();
186                let compact =
187                    CompactLayout::from_layout(&layout, CapabilityFlags::empty()).unwrap();
188                assert_eq!(compact.get_alignment(), align);
189                assert_eq!(compact.get_alignment_log2(), exp as usize);
190            }
191        }
192    }
193
194    #[test]
195    fn test_serialization_roundtrip() {
196        let layout = Layout::from_size_align(128, 16).unwrap();
197        let capabilities = CapabilityFlags::all();
198        let compact = CompactLayout::from_layout(&layout, capabilities).unwrap();
199        let bytes = compact.to_le_bytes();
200        let restored = CompactLayout::from_le_bytes(bytes);
201        assert_eq!(compact, restored);
202        assert_eq!(restored.get_capabilities(), capabilities);
203        assert_eq!(restored.into_layout(), Some(layout));
204        assert_eq!(size_of::<CompactLayout>(), size_of::<usize>());
205        assert_eq!(restored.get_size(), 128);
206        assert_eq!(restored.get_alignment(), 16);
207    }
208
209    #[test]
210    #[allow(clippy::clone_on_copy)]
211    fn test_clone_and_copy() {
212        let layout = Layout::from_size_align(32, 4).unwrap();
213        let compact = CompactLayout::from_layout(&layout, CapabilityFlags::empty()).unwrap();
214        let cloned = compact.clone();
215        let copied = compact;
216        assert_eq!(compact, cloned);
217        assert_eq!(compact, copied);
218    }
219
220    #[test]
221    fn test_multiple_size_alignment_combinations() {
222        let sizes = [0, 1, 16, 256, 4096];
223        let alignments = [1, 2, 4, 8, 16, 32, 64];
224
225        for &size in &sizes {
226            for &align in &alignments {
227                if size <= CompactLayout::MAXIMUM_SIZE && align <= CompactLayout::MAXIMUM_ALIGNMENT
228                {
229                    let layout = Layout::from_size_align(size, align).unwrap();
230                    let compact =
231                        CompactLayout::from_layout(&layout, CapabilityFlags::empty()).unwrap();
232                    assert_eq!(compact.get_size(), size);
233                    assert_eq!(compact.get_alignment(), align);
234                }
235            }
236        }
237    }
238}