alpha2_host_core/export/
budget.rs1use std::sync::Arc;
5use std::sync::atomic::{AtomicU64, Ordering};
6
7use alpha2_os::MemoryCapacity;
8
9pub const MIN_FRAME_BYTES: u64 = 32 << 20;
13
14#[derive(Clone, Debug)]
17pub struct FrameBudget(Arc<AtomicU64>);
18
19impl FrameBudget {
20 #[must_use]
22 pub fn new(bytes: u64) -> Self {
23 Self(Arc::new(AtomicU64::new(bytes.max(MIN_FRAME_BYTES))))
24 }
25
26 #[must_use]
29 pub fn of_memory(capacity: &MemoryCapacity, ceiling: u64) -> Self {
30 Self::new(
31 capacity
32 .headroom()
33 .map_or(ceiling, |free| (free / 4).min(ceiling)),
34 )
35 }
36
37 #[must_use]
39 pub fn bytes(&self) -> u64 {
40 self.0.load(Ordering::Acquire)
41 }
42
43 pub fn halve(&self) {
45 let _ = self
46 .0
47 .try_update(Ordering::AcqRel, Ordering::Acquire, |bytes| {
48 Some((bytes / 2).max(MIN_FRAME_BYTES))
49 });
50 }
51
52 #[must_use]
54 pub fn is_shared(&self) -> bool {
55 Arc::strong_count(&self.0) > 1
56 }
57}
58
59#[cfg(test)]
60mod tests {
61 use super::{FrameBudget, MIN_FRAME_BYTES};
62 use alpha2_os::MemoryCapacity;
63
64 #[test]
65 fn a_budget_takes_a_quarter_of_the_headroom_up_to_its_ceiling_and_halves_to_the_floor() {
66 let capacity = MemoryCapacity {
67 available_bytes: Some(1 << 30),
68 ..MemoryCapacity::default()
69 };
70 assert_eq!(
71 FrameBudget::of_memory(&capacity, 1 << 30).bytes(),
72 256 << 20
73 );
74 assert_eq!(
75 FrameBudget::of_memory(&capacity, 64 << 20).bytes(),
76 64 << 20
77 );
78 let unknown = FrameBudget::of_memory(&MemoryCapacity::default(), 512 << 20);
79 assert_eq!(unknown.bytes(), 512 << 20);
80 let shared = unknown.clone();
81 assert!(unknown.is_shared());
82 for _ in 0..8 {
83 shared.halve();
84 }
85 assert_eq!(unknown.bytes(), MIN_FRAME_BYTES);
86 drop(shared);
87 assert!(!unknown.is_shared());
88 assert_eq!(FrameBudget::new(0).bytes(), MIN_FRAME_BYTES);
89 }
90}