Skip to main content

spatialrust_gpu/
resource_cache.rs

1//! Byte-bounded retention shared by storage-buffer and image-texture pools.
2
3use std::collections::HashMap;
4use std::hash::Hash;
5
6/// Default retained-byte budget for each GPU resource pool (64 MiB).
7pub const DEFAULT_GPU_POOL_BUDGET_BYTES: u64 = 64 * 1024 * 1024;
8const MAX_PER_KEY: usize = 8;
9
10/// Snapshot of one pool's retained resources and lifetime acquisition counters.
11///
12/// Bytes describe requested buffer sizes or RGBA8 texel payloads, excluding
13/// driver overhead, live caller-owned resources, uniforms, and readback staging.
14#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
15pub struct GpuResourcePoolStats {
16    /// Maximum bytes retained after resources are recycled.
17    pub budget_bytes: u64,
18    /// Bytes currently retained for reuse.
19    pub cached_bytes: u64,
20    /// Resources currently retained for reuse.
21    pub cached_resources: usize,
22    /// Device allocations requested through this pool since its creation.
23    pub allocation_count: u64,
24    /// Acquisitions satisfied by an already retained resource.
25    pub reuse_count: u64,
26    /// Recycled or cached resources dropped instead of retained.
27    pub discarded_count: u64,
28}
29
30#[derive(Debug)]
31pub(crate) struct ResourceCache<K, V> {
32    free: HashMap<K, Vec<(u64, V)>>,
33    stats: GpuResourcePoolStats,
34}
35
36impl<K: Eq + Hash, V> ResourceCache<K, V> {
37    pub(crate) fn new(budget_bytes: u64) -> Self {
38        Self {
39            free: HashMap::new(),
40            stats: GpuResourcePoolStats { budget_bytes, ..Default::default() },
41        }
42    }
43
44    pub(crate) fn take(&mut self, key: &K) -> Option<V> {
45        let values = self.free.get_mut(key)?;
46        let (bytes, value) = values.pop()?;
47        if values.is_empty() {
48            self.free.remove(key);
49        }
50        self.stats.cached_bytes -= bytes;
51        self.stats.cached_resources -= 1;
52        self.stats.reuse_count = self.stats.reuse_count.saturating_add(1);
53        Some(value)
54    }
55
56    pub(crate) fn record_allocation(&mut self) {
57        self.stats.allocation_count = self.stats.allocation_count.saturating_add(1);
58    }
59
60    pub(crate) fn record_discard(&mut self) {
61        self.stats.discarded_count = self.stats.discarded_count.saturating_add(1);
62    }
63
64    pub(crate) fn put(&mut self, key: K, bytes: u64, value: V) {
65        if bytes == 0
66            || bytes > self.stats.budget_bytes.saturating_sub(self.stats.cached_bytes)
67            || self.free.get(&key).is_some_and(|values| values.len() >= MAX_PER_KEY)
68        {
69            self.record_discard();
70            return;
71        }
72        self.free.entry(key).or_default().push((bytes, value));
73        self.stats.cached_bytes += bytes;
74        self.stats.cached_resources += 1;
75    }
76
77    pub(crate) fn stats(&self) -> GpuResourcePoolStats {
78        self.stats
79    }
80
81    pub(crate) fn clear(&mut self) {
82        self.stats.discarded_count =
83            self.stats.discarded_count.saturating_add(self.stats.cached_resources as u64);
84        self.free.clear();
85        self.stats.cached_bytes = 0;
86        self.stats.cached_resources = 0;
87    }
88
89    pub(crate) fn set_budget(&mut self, budget_bytes: u64) {
90        self.stats.budget_bytes = budget_bytes;
91        if self.stats.cached_bytes > budget_bytes {
92            self.clear();
93        }
94    }
95}
96
97#[cfg(test)]
98mod tests {
99    use super::*;
100
101    #[test]
102    fn budget_boundary_and_key_churn_bound_retained_memory() {
103        let mut cache = ResourceCache::new(16);
104        cache.put(1, 8, 10);
105        cache.put(2, 8, 20);
106        for key in 3..10_000 {
107            cache.put(key, 4, 30);
108        }
109        assert_eq!(cache.stats().cached_bytes, 16);
110        assert_eq!(cache.free.len(), 2);
111        assert_eq!(cache.take(&1), Some(10));
112        assert!(!cache.free.contains_key(&1));
113        assert_eq!(cache.take(&1), None);
114        assert_eq!(cache.stats().reuse_count, 1);
115        cache.put(3, 8, 30);
116        assert_eq!(cache.stats().cached_bytes, 16);
117        assert_eq!(cache.stats().cached_resources, 2);
118    }
119
120    #[test]
121    fn per_key_limit_shrinking_and_zero_budget_keep_lifetime_counters() {
122        let mut cache = ResourceCache::new(u64::MAX);
123        for _ in 0..10 {
124            cache.record_allocation();
125            cache.put(1, 4, ());
126        }
127        assert_eq!(cache.stats().cached_resources, MAX_PER_KEY);
128        assert_eq!(cache.stats().discarded_count, 2);
129        cache.set_budget(31);
130        assert_eq!(cache.stats().cached_bytes, 0);
131        assert!(cache.free.is_empty());
132        assert_eq!(cache.stats().allocation_count, 10);
133        assert_eq!(cache.stats().discarded_count, 10);
134        cache.set_budget(0);
135        cache.put(2, 4, ());
136        cache.put(3, 0, ());
137        assert_eq!(cache.stats().cached_resources, 0);
138        assert_eq!(cache.stats().discarded_count, 12);
139        cache.set_budget(4);
140        cache.put(4, 4, ());
141        cache.clear();
142        assert_eq!(cache.stats().budget_bytes, 4);
143        assert_eq!(cache.stats().cached_resources, 0);
144    }
145}