swage_core/memory/
pfn_offset.rs

1use crate::memory::keyed_cache::KeyedCache;
2use crate::memory::mem_configuration::MemConfiguration;
3use std::cell::RefCell;
4
5type CacheKey = (MemConfiguration, u64);
6type CacheValue = Option<usize>;
7
8/// Physical frame number (PFN) offset configuration.
9///
10/// Represents either a fixed offset or a dynamically calculated offset
11/// that is cached for performance. Fixed offsets disable runtime calculation.
12#[derive(Clone, Debug)]
13pub enum PfnOffset {
14    /// A constant offset that never changes
15    Fixed(usize),
16    /// A dynamically calculated offset with caching
17    ///
18    /// Stores the cached value and the configuration key used to compute it
19    Dynamic(Box<RefCell<Option<(CacheValue, CacheKey)>>>),
20}
21
22/// Trait for types that provide cached PFN offset access.
23pub trait CachedPfnOffset {
24    /// Returns a reference to the PFN offset.
25    fn cached_offset(&self) -> &PfnOffset;
26}
27
28/// A cache for the PFN offset keyed by memory configuration and conflict threshold.
29/// This allows the implementation to store a fixed PFN offset, effectively disabling logic around PFN offset calculation.
30impl<T> KeyedCache<usize, (MemConfiguration, u64)> for T
31where
32    T: CachedPfnOffset,
33{
34    fn get_cached(&self, key: (MemConfiguration, u64)) -> Option<usize> {
35        match self.cached_offset() {
36            PfnOffset::Fixed(offset) => Some(*offset),
37            PfnOffset::Dynamic(pfn_offset) => {
38                let state = pfn_offset.borrow();
39                match state.as_ref() {
40                    Some((offset, cfg)) if offset.is_some() && *cfg == key => Some(offset.unwrap()),
41                    _ => None,
42                }
43            }
44        }
45    }
46    fn put(&self, state: Option<usize>, key: (MemConfiguration, u64)) -> Option<usize> {
47        match self.cached_offset() {
48            PfnOffset::Fixed(_) => panic!("Fixed offset should not be set"),
49            PfnOffset::Dynamic(cell) => {
50                let mut cell = cell.borrow_mut();
51                *cell = Some((state, key));
52                state
53            }
54        }
55    }
56}