Skip to main content

akar_common/
memory.rs

1//! Memory management utilities for the buffer manager.
2//!
3//! Tracks allocated memory and provides backpressure hints.
4
5use std::sync::atomic::{AtomicU64, Ordering};
6
7/// A simple memory tracker for the database instance.
8#[derive(Debug)]
9pub struct MemoryManager {
10    total_allocated: AtomicU64,
11    max_memory: u64,
12}
13
14impl MemoryManager {
15    pub fn new(max_memory: u64) -> Self {
16        Self {
17            total_allocated: AtomicU64::new(0),
18            max_memory,
19        }
20    }
21
22    pub fn max_memory(&self) -> u64 {
23        self.max_memory
24    }
25
26    pub fn total_allocated(&self) -> u64 {
27        self.total_allocated.load(Ordering::Relaxed)
28    }
29
30    pub fn allocate(&self, amount: u64) {
31        self.total_allocated.fetch_add(amount, Ordering::Relaxed);
32    }
33
34    pub fn deallocate(&self, amount: u64) {
35        self.total_allocated.fetch_sub(amount, Ordering::Relaxed);
36    }
37
38    pub fn is_under_limit(&self) -> bool {
39        self.total_allocated() <= self.max_memory
40    }
41}
42
43impl Default for MemoryManager {
44    fn default() -> Self {
45        // Default to 80% of available system memory (approximate).
46        Self::new(u64::MAX)
47    }
48}