tensor4all_tensorbackend/
memory.rs1#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
10pub struct AllocatorPressureRelief {
11 pub supported: bool,
13 pub released_bytes: Option<usize>,
15 pub success: Option<bool>,
17}
18
19pub fn release_process_allocator_cached_memory() -> AllocatorPressureRelief {
38 allocator_pressure_relief()
39}
40
41#[cfg(target_os = "macos")]
42fn allocator_pressure_relief() -> AllocatorPressureRelief {
43 use std::ffi::c_void;
44
45 extern "C" {
46 fn malloc_default_zone() -> *mut c_void;
47 fn malloc_zone_pressure_relief(zone: *mut c_void, goal: usize) -> usize;
48 }
49
50 unsafe {
51 let zone = malloc_default_zone();
52 if zone.is_null() {
53 AllocatorPressureRelief {
54 supported: true,
55 released_bytes: Some(0),
56 success: Some(false),
57 }
58 } else {
59 let released_bytes = malloc_zone_pressure_relief(zone, 0);
60 AllocatorPressureRelief {
61 supported: true,
62 released_bytes: Some(released_bytes),
63 success: Some(released_bytes > 0),
64 }
65 }
66 }
67}
68
69#[cfg(target_os = "linux")]
70fn allocator_pressure_relief() -> AllocatorPressureRelief {
71 extern "C" {
72 fn malloc_trim(pad: usize) -> i32;
73 }
74
75 let success = unsafe { malloc_trim(0) != 0 };
76 AllocatorPressureRelief {
77 supported: true,
78 released_bytes: None,
79 success: Some(success),
80 }
81}
82
83#[cfg(not(any(target_os = "macos", target_os = "linux")))]
84fn allocator_pressure_relief() -> AllocatorPressureRelief {
85 AllocatorPressureRelief {
86 supported: false,
87 released_bytes: None,
88 success: None,
89 }
90}
91
92#[cfg(test)]
93mod tests {
94 use super::release_process_allocator_cached_memory;
95
96 #[test]
97 fn reports_platform_support() {
98 let report = release_process_allocator_cached_memory();
99 assert_eq!(
100 report.supported,
101 cfg!(any(target_os = "macos", target_os = "linux"))
102 );
103 }
104}