summaryrefslogtreecommitdiffhomepage
path: root/talpid-windows/src/io.rs
blob: 1bcffb30d345c0f8fb1d532f06532212a7826915 (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
use std::{io, mem};
use windows_sys::Win32::System::IO::OVERLAPPED;

use crate::sync::Event;

/// Abstraction over `OVERLAPPED`.
pub struct Overlapped {
    overlapped: OVERLAPPED,
    event: Option<Event>,
}

unsafe impl Send for Overlapped {}
unsafe impl Sync for Overlapped {}

impl Overlapped {
    /// Creates an `OVERLAPPED` object with `hEvent` set.
    pub fn new(event: Option<Event>) -> io::Result<Self> {
        let mut overlapped = Overlapped {
            overlapped: unsafe { mem::zeroed() },
            event: None,
        };
        overlapped.set_event(event);
        Ok(overlapped)
    }

    /// Borrows the underlying `OVERLAPPED` object.
    pub fn as_mut_ptr(&mut self) -> *mut OVERLAPPED {
        &mut self.overlapped
    }

    /// Returns a reference to the associated event.
    pub fn get_event(&self) -> Option<&Event> {
        self.event.as_ref()
    }

    /// Sets the event object for the underlying `OVERLAPPED` object (i.e., `hEvent`)
    fn set_event(&mut self, event: Option<Event>) {
        match event {
            Some(event) => {
                self.overlapped.hEvent = event.as_raw();
                self.event = Some(event);
            }
            None => {
                self.overlapped.hEvent = 0;
                self.event = None;
            }
        }
    }
}