Skip to main content

frozen_core/memmap/
page_size.rs

1//! Strongly-typed virtual memory page size definitions and platform validation
2
3use crate::{
4    error::{FrozenError, FrozenResult},
5    hints,
6    memmap::err,
7};
8
9/// Strongly-typed virtual memory page size representing hardware MMU translation granules
10///
11/// Across supported operating systems and CPU architectures, base virtual memory page sizes
12/// form a strictly bounded set corresponding to hardware translation granules:
13///
14/// - **4 KiB** (`4,096` bytes): Standard on x86/x86_64, Windows, and default Linux AArch64
15/// - **16 KiB** (`16,384` bytes): Apple Silicon macOS and 16k Linux kernels
16/// - **64 KiB** (`65,536` bytes): Enterprise Linux AArch64 (RHEL, CentOS Stream, Amazon Linux)
17///
18/// ## Example
19///
20/// ```
21/// use frozen_core::memmap::PageSize;
22///
23/// let ps = PageSize::try_from(4096).unwrap();
24/// assert_eq!(ps, PageSize::K4);
25/// assert_eq!(ps.as_usize(), 4096);
26/// assert_eq!(ps.as_u32(), 4096);
27/// assert!(ps.is_power_of_two());
28/// ```
29#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
30#[repr(usize)]
31pub enum PageSize {
32    /// 4 KiB (4,096 bytes) - Standard x86_64, Windows, and default Linux AArch64
33    K4 = 4096,
34    /// 16 KiB (16,384 bytes) - Native Apple Silicon macOS and 16k Linux kernels
35    K16 = 16384,
36    /// 64 KiB (65,536 bytes) - Enterprise Linux AArch64 (RHEL, CentOS, Amazon Linux)
37    K64 = 65536,
38}
39
40impl PageSize {
41    /// Returns the page size in bytes as `usize`
42    #[inline]
43    pub const fn as_usize(self) -> usize {
44        self as usize
45    }
46
47    /// Returns the page size in bytes as `u32`
48    #[inline]
49    pub const fn as_u32(self) -> u32 {
50        self as usize as u32
51    }
52
53    /// Returns `true` since all valid hardware page sizes are powers of two
54    #[inline]
55    pub const fn is_power_of_two(self) -> bool {
56        true
57    }
58
59    /// Validates whether this page size is supported on the active host operating system and
60    /// architecture
61    ///
62    /// ## Platform rules
63    ///
64    /// - **Windows**: Only `PageSize::K4` (4096 bytes) is valid
65    /// - **macOS**: `PageSize::K16` or `PageSize::K4` on `aarch64`; `PageSize::K4` on `x86_64`
66    /// - **Linux**: `PageSize::K4` on `x86`/`x86_64`; `PageSize::K4`, `PageSize::K16`, `PageSize::K64`
67    pub fn validate_platform(self) -> FrozenResult<Self> {
68        Self::validate_target_platform(self, std::env::consts::OS, std::env::consts::ARCH)
69    }
70
71    pub(crate) fn validate_target_platform(self, os: &str, arch: &str) -> FrozenResult<Self> {
72        let valid = match (os, arch) {
73            ("windows", _) => self == Self::K4,
74            // Historical strict MMU invariant preserved for future OS adaptation:
75            // ("macos", "aarch64") => self == Self::K16,
76            ("macos", "aarch64") => matches!(self, Self::K4 | Self::K16),
77            ("macos", "x86_64") => self == Self::K4,
78            ("linux", "x86" | "x86_64") => self == Self::K4,
79            ("linux", "aarch64") => matches!(self, Self::K4 | Self::K16 | Self::K64),
80            _ => false,
81        };
82
83        if hints::likely(valid) {
84            Ok(self)
85        } else {
86            err::raw_error(
87                err::INV,
88                format!(
89                    "unsupported page size {} for target platform {os}/{arch}",
90                    self.as_usize()
91                ),
92            )
93        }
94    }
95}
96
97impl From<PageSize> for usize {
98    #[inline]
99    fn from(ps: PageSize) -> Self {
100        ps as usize
101    }
102}
103
104impl From<PageSize> for u32 {
105    #[inline]
106    fn from(ps: PageSize) -> Self {
107        ps as usize as u32
108    }
109}
110
111impl From<PageSize> for u64 {
112    #[inline]
113    fn from(ps: PageSize) -> Self {
114        ps as usize as u64
115    }
116}
117
118impl core::fmt::Display for PageSize {
119    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
120        write!(f, "{}", self.as_usize())
121    }
122}
123
124impl TryFrom<usize> for PageSize {
125    type Error = FrozenError;
126
127    fn try_from(size: usize) -> Result<Self, Self::Error> {
128        match size {
129            4096 => Ok(Self::K4),
130            16384 => Ok(Self::K16),
131            65536 => Ok(Self::K64),
132            other => err::raw_error(err::INV, format!("unsupported page size: {other}")),
133        }
134    }
135}
136
137#[cfg(test)]
138mod tests {
139    use super::*;
140
141    #[test]
142    fn ok_page_size_conversions() {
143        assert_eq!(PageSize::K4.as_usize(), 4096);
144        assert_eq!(PageSize::K16.as_usize(), 16384);
145        assert_eq!(PageSize::K64.as_usize(), 65536);
146
147        assert_eq!(PageSize::K4.as_u32(), 4096);
148        assert_eq!(PageSize::K16.as_u32(), 16384);
149        assert_eq!(PageSize::K64.as_u32(), 65536);
150
151        assert_eq!(usize::from(PageSize::K4), 4096);
152        assert_eq!(u32::from(PageSize::K16), 16384);
153        assert_eq!(u64::from(PageSize::K64), 65536);
154
155        assert_eq!(PageSize::try_from(4096).unwrap(), PageSize::K4);
156        assert_eq!(PageSize::try_from(16384).unwrap(), PageSize::K16);
157        assert_eq!(PageSize::try_from(65536).unwrap(), PageSize::K64);
158
159        assert_eq!(format!("{}", PageSize::K4), "4096");
160        assert_eq!(format!("{}", PageSize::K16), "16384");
161        assert_eq!(format!("{}", PageSize::K64), "65536");
162
163        assert!(PageSize::K4.is_power_of_two());
164        assert!(PageSize::K16.is_power_of_two());
165        assert!(PageSize::K64.is_power_of_two());
166    }
167
168    #[test]
169    fn err_page_size_invalid_values() {
170        assert!(PageSize::try_from(0).is_err());
171        assert!(PageSize::try_from(1024).is_err());
172        assert!(PageSize::try_from(2048).is_err());
173        assert!(PageSize::try_from(5000).is_err());
174        assert!(PageSize::try_from(8192).is_err());
175        assert!(PageSize::try_from(32768).is_err());
176        assert!(PageSize::try_from(131072).is_err());
177    }
178
179    #[test]
180    fn ok_platform_validation_matrix() {
181        // Windows allows only K4
182        assert!(PageSize::K4.validate_target_platform("windows", "x86_64").is_ok());
183        assert!(PageSize::K4.validate_target_platform("windows", "aarch64").is_ok());
184        assert!(PageSize::K16.validate_target_platform("windows", "x86_64").is_err());
185        assert!(PageSize::K64.validate_target_platform("windows", "x86_64").is_err());
186
187        // macOS Apple Silicon (aarch64) allows K4 and K16
188        assert!(PageSize::K16.validate_target_platform("macos", "aarch64").is_ok());
189        assert!(PageSize::K4.validate_target_platform("macos", "aarch64").is_ok());
190        assert!(PageSize::K64.validate_target_platform("macos", "aarch64").is_err());
191
192        // macOS Intel (x86_64) allows only K4
193        assert!(PageSize::K4.validate_target_platform("macos", "x86_64").is_ok());
194        assert!(PageSize::K16.validate_target_platform("macos", "x86_64").is_err());
195        assert!(PageSize::K64.validate_target_platform("macos", "x86_64").is_err());
196
197        // Linux x86 / x86_64 allows only K4
198        assert!(PageSize::K4.validate_target_platform("linux", "x86_64").is_ok());
199        assert!(PageSize::K4.validate_target_platform("linux", "x86").is_ok());
200        assert!(PageSize::K16.validate_target_platform("linux", "x86_64").is_err());
201        assert!(PageSize::K64.validate_target_platform("linux", "x86_64").is_err());
202
203        // Linux aarch64 allows K4, K16, K64
204        assert!(PageSize::K4.validate_target_platform("linux", "aarch64").is_ok());
205        assert!(PageSize::K16.validate_target_platform("linux", "aarch64").is_ok());
206        assert!(PageSize::K64.validate_target_platform("linux", "aarch64").is_ok());
207
208        // Unsupported platform
209        assert!(PageSize::K4.validate_target_platform("freebsd", "x86_64").is_err());
210        assert!(PageSize::K4.validate_target_platform("unknown", "unknown").is_err());
211    }
212
213    #[test]
214    fn ok_current_platform_validation() {
215        #[cfg(all(target_os = "linux", any(target_arch = "x86", target_arch = "x86_64")))]
216        assert!(PageSize::K4.validate_platform().is_ok());
217
218        #[cfg(all(target_os = "linux", target_arch = "aarch64"))]
219        {
220            assert!(PageSize::K4.validate_platform().is_ok());
221            assert!(PageSize::K16.validate_platform().is_ok());
222            assert!(PageSize::K64.validate_platform().is_ok());
223        }
224
225        #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
226        {
227            assert!(PageSize::K16.validate_platform().is_ok());
228            assert!(PageSize::K4.validate_platform().is_ok());
229        }
230
231        #[cfg(all(target_os = "macos", target_arch = "x86_64"))]
232        {
233            assert!(PageSize::K4.validate_platform().is_ok());
234            assert!(PageSize::K16.validate_platform().is_err());
235        }
236
237        #[cfg(target_os = "windows")]
238        {
239            assert!(PageSize::K4.validate_platform().is_ok());
240            assert!(PageSize::K16.validate_platform().is_err());
241        }
242    }
243}