Skip to main content

redup_bootstrap/
memory_config.rs

1//! Память процесса: настройка системного аллокатора.
2
3use redup_config::Config;
4
5/// Управление памятью процесса.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Config)]
7pub struct MemoryConfig {
8    /// Порог, с которого системный аллокатор выделяет память напрямую у операционной системы,
9    /// в байтах. Крупные буферы выше порога возвращаются системе сразу после освобождения.
10    /// `~` или ноль — не трогать настройку аллокатора.
11    mmap_threshold: Option<u64>,
12}
13
14impl Default for MemoryConfig {
15    fn default() -> Self {
16        Self {
17            mmap_threshold: Some(2 * 1024 * 1024),
18        }
19    }
20}
21
22impl MemoryConfig {
23    /// Действующий порог mmap в байтах; `None` — настройка выключена (`~` или ноль).
24    pub fn mmap_threshold(&self) -> Option<u64> {
25        self.mmap_threshold.filter(|threshold| *threshold > 0)
26    }
27}
28
29#[cfg(test)]
30mod tests {
31    use redup_config::{Source, load};
32
33    use super::MemoryConfig;
34
35    /// Читает секцию `memory` из временного файла.
36    fn read(section: &str) -> MemoryConfig {
37        let directory = tempfile::tempdir().expect("a temporary directory");
38        std::fs::write(
39            directory.path().join("config.yaml"),
40            format!("memory:\n{section}"),
41        )
42        .expect("the configuration file");
43        load::<MemoryConfig>(&Source::directory(directory.path()))
44            .expect("the configuration is accepted")
45            .value
46    }
47
48    #[test]
49    fn threshold_is_two_mebibytes_by_default() {
50        assert_eq!(
51            MemoryConfig::default().mmap_threshold(),
52            Some(2 * 1024 * 1024)
53        );
54        assert_eq!(
55            read("\x20 mmapThreshold: 4Mi\n").mmap_threshold(),
56            Some(4 * 1024 * 1024)
57        );
58    }
59
60    #[test]
61    fn null_disables_the_threshold() {
62        assert_eq!(read("\x20 mmapThreshold: ~\n").mmap_threshold(), None);
63    }
64
65    #[test]
66    fn zero_disables_the_threshold() {
67        assert_eq!(read("\x20 mmapThreshold: 0\n").mmap_threshold(), None);
68    }
69}