Skip to main content

reloaded_memory_buffers/structs/params/
buffer_search_settings.rs

1use crate::utilities::{cached::get_sys_info, mathematics};
2
3/// Settings to pass to buffer search mechanisms.
4#[derive(Debug, Clone, Copy)]
5#[repr(C)]
6pub struct BufferSearchSettings {
7    /// Minimum address of the allocation.
8    pub min_address: usize,
9
10    /// Maximum address of the allocation.
11    pub max_address: usize,
12
13    /// Required size of the data.
14    pub size: u32,
15}
16
17impl BufferSearchSettings {
18    /// Initializes the buffer allocator with default settings.
19    pub fn new() -> Self {
20        Self {
21            min_address: 0,
22            max_address: get_sys_info().max_address,
23            size: 4096,
24        }
25    }
26
27    /// Creates settings such that the returned buffer will always be within `proximity` bytes of `target`.
28    ///
29    /// # Arguments
30    ///
31    /// * `proximity` - Max proximity (number of bytes) to target.
32    /// * `target` - Target address.
33    /// * `size` - Size required in the settings.
34    ///
35    /// # Returns
36    ///
37    /// * `BufferSearchSettings` - Settings that would satisfy this search.
38    pub fn from_proximity(proximity: usize, target: usize, size: usize) -> Self {
39        Self {
40            max_address: mathematics::add_with_overflow_cap(target, proximity),
41            min_address: mathematics::subtract_with_underflow_cap(target, proximity),
42            size: size as u32,
43        }
44    }
45}
46
47impl Default for BufferSearchSettings {
48    fn default() -> Self {
49        Self::new()
50    }
51}
52
53#[cfg(test)]
54mod tests {
55    use super::*;
56
57    #[test]
58    fn test_default_settings() {
59        let settings = BufferSearchSettings::new();
60        assert_eq!(settings.min_address, 0);
61        assert_eq!(settings.max_address, get_sys_info().max_address);
62        assert_eq!(settings.size, 4096);
63    }
64
65    #[test]
66    fn test_from_proximity() {
67        let proximity: usize = 1000;
68        let target: usize = 2000;
69        let size: usize = 3000;
70        let settings = BufferSearchSettings::from_proximity(proximity, target, size);
71
72        assert_eq!(
73            settings.max_address,
74            mathematics::add_with_overflow_cap(target, proximity)
75        );
76        assert_eq!(
77            settings.min_address,
78            mathematics::subtract_with_underflow_cap(target, proximity)
79        );
80        assert_eq!(settings.size, size as u32);
81    }
82}