use windows::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE};
#[derive(Debug)]
pub struct OwnedHandle {
handle: HANDLE,
close_on_drop: bool,
}
impl OwnedHandle {
pub fn new(handle: HANDLE) -> Self {
Self {
handle,
close_on_drop: true,
}
}
pub fn with_ownership(handle: HANDLE, close_on_drop: bool) -> Self {
Self {
handle,
close_on_drop,
}
}
pub fn borrowed(handle: HANDLE) -> Self {
Self {
handle,
close_on_drop: false,
}
}
pub fn raw(&self) -> HANDLE {
self.handle
}
pub fn set_close_on_drop(&mut self, close_on_drop: bool) {
self.close_on_drop = close_on_drop;
}
pub fn close_on_drop(&self) -> bool {
self.close_on_drop
}
}
impl Drop for OwnedHandle {
fn drop(&mut self) {
if self.close_on_drop && !self.handle.is_invalid() && self.handle != INVALID_HANDLE_VALUE {
let _ = unsafe { CloseHandle(self.handle) };
}
}
}
unsafe impl Send for OwnedHandle {}
unsafe impl Sync for OwnedHandle {}