ps_alloc/
header.rs

1use crate::marker::{MARKER_FREE, MARKER_USED};
2
3/// Metadata header prefixed to every allocation.
4///
5/// Stores the allocation state via `marker` (`MARKER_USED` or `MARKER_FREE`) and the
6/// total allocation size in bytes (including this header and alignment padding) in `size`.
7///
8/// Aligned to 16 bytes to guarantee all allocations are aligned to 16 bytes.
9#[repr(align(16))]
10pub struct AllocationHeader {
11    marker: [u8; 8],
12    size: usize,
13}
14
15impl AllocationHeader {
16    /// Checks the allocation size stored in this header.
17    ///
18    /// Marker checks are best-effort debugging aids.
19    /// Reading this header is undefined behavior if the pointer is invalid.
20    #[inline]
21    pub const fn get_size(&self) -> usize {
22        self.size
23    }
24
25    /// Checks whether this header is marked as free (deallocated).
26    ///
27    /// Marker checks are best-effort debugging aids.
28    /// Reading this header is undefined behavior if the pointer is invalid.
29    #[inline]
30    pub fn is_marked_as_free(&self) -> bool {
31        self.marker == MARKER_FREE
32    }
33
34    /// Checks whether this header is marked as used (allocated).
35    ///
36    /// Marker checks are best-effort debugging aids.
37    /// Reading this header is undefined behavior if the pointer is invalid.
38    #[inline]
39    pub fn is_marked_as_used(&self) -> bool {
40        self.marker == MARKER_USED
41    }
42
43    #[inline]
44    pub const fn mark_as_free(&mut self) {
45        self.marker = MARKER_FREE;
46    }
47
48    #[inline]
49    pub const fn mark_as_used(&mut self) {
50        self.marker = MARKER_USED;
51    }
52
53    #[inline]
54    pub const fn set_size(&mut self, new_size: usize) {
55        self.size = new_size;
56    }
57}
58
59pub const HEADER_SIZE: usize = std::mem::size_of::<AllocationHeader>();