summaryrefslogtreecommitdiffhomepage
path: root/talpid-windows/src/sync.rs
blob: 567f556a73c682850a5580e00855e032c750b075 (plain)
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#![allow(clippy::undocumented_unsafe_blocks)] // Remove me if you dare.

use std::{
    io,
    os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle, RawHandle},
    ptr,
};
use windows_sys::Win32::{
    Foundation::{DUPLICATE_SAME_ACCESS, DuplicateHandle},
    System::Threading::{CreateEventW, GetCurrentProcess, SetEvent},
};

/// Windows event object
pub struct Event(OwnedHandle);

unsafe impl Send for Event {}
unsafe impl Sync for Event {}

impl Event {
    /// Create a new event object using `CreateEventW`
    pub fn new(manual_reset: bool, initial_state: bool) -> io::Result<Self> {
        let event = unsafe {
            CreateEventW(
                ptr::null_mut(),
                i32::from(manual_reset),
                i32::from(initial_state),
                ptr::null(),
            )
        };
        if event.is_null() {
            return Err(io::Error::last_os_error());
        }
        // SAFETY: `event` is a valid handle since `CreateEventW` succeeded
        Ok(Self(unsafe { OwnedHandle::from_raw_handle(event) }))
    }

    /// Signal the event object
    pub fn set(&self) -> io::Result<()> {
        // SAFETY: `self.0` is a valid handle
        if unsafe { SetEvent(self.0.as_raw_handle()) } == 0 {
            return Err(io::Error::last_os_error());
        }
        Ok(())
    }

    /// Duplicate the event object with `DuplicateHandle()`
    pub fn duplicate(&self) -> io::Result<Event> {
        let mut new_event = ptr::null_mut();
        let status = unsafe {
            DuplicateHandle(
                GetCurrentProcess(),
                self.0.as_raw_handle(),
                GetCurrentProcess(),
                &mut new_event,
                0,
                0,
                DUPLICATE_SAME_ACCESS,
            )
        };
        if status == 0 {
            return Err(io::Error::last_os_error());
        }
        // SAFETY: `new_event` is a valid handle since `DuplicateHandle` succeeded
        Ok(Event(unsafe { OwnedHandle::from_raw_handle(new_event) }))
    }
}

impl AsRawHandle for Event {
    fn as_raw_handle(&self) -> RawHandle {
        self.0.as_raw_handle()
    }
}