zng_view/
low_memory.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
//! Low memory event for desktop systems

#[cfg(windows)]
mod windows {
    use windows::Win32::{
        Foundation::{CloseHandle, BOOL, HANDLE},
        System::Memory::*,
    };

    pub struct LowMemoryMonitor {
        handle: HANDLE,
        is_low: bool,
    }
    impl LowMemoryMonitor {
        pub fn new() -> Option<LowMemoryMonitor> {
            // SAFETY: its save, strongly typed call.
            let handle = match unsafe { CreateMemoryResourceNotification(LowMemoryResourceNotification) } {
                Ok(h) => h,
                Err(e) => {
                    tracing::error!("cannot create memory monitor, {e}");
                    return None;
                }
            };

            if handle.is_invalid() {
                tracing::error!("cannot create memory monitor, handle is invalid");
                return None;
            }

            Some(Self { handle, is_low: false })
        }

        pub fn notify(&mut self) -> bool {
            let mut is_low = BOOL::from(false);
            // SAFETY: strongly typed function called as documented in CreateMemoryResourceNotification msdn page.
            if let Err(e) = unsafe { QueryMemoryResourceNotification(self.handle, &mut is_low) } {
                tracing::error!("failed to query memory monitor, {e}");
                is_low = BOOL::from(false);
            }
            if self.is_low != is_low.as_bool() {
                self.is_low = is_low.as_bool();
                return self.is_low;
            }
            false
        }
    }
    impl Drop for LowMemoryMonitor {
        fn drop(&mut self) {
            // SAFETY: strongly typed function called as documented in CreateMemoryResourceNotification msdn page.
            if let Err(e) = unsafe { CloseHandle(self.handle) } {
                tracing::error!("failed to close memory monitor, {e}");
            }
        }
    }
}

#[cfg(windows)]
pub use windows::LowMemoryMonitor;