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
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
use super::*;
use std::sync::atomic::{AtomicBool, Ordering};
use std::mem::size_of;
use std::time::{Duration, Instant};

#[doc(hidden)]
pub struct GenericEvent<'a> {
    pub uid: u8,
    pub ptr: *mut c_void,
    pub interface: &'a EventImpl,
}
impl<'a> Drop for GenericEvent<'a> {
    fn drop(&mut self) {
        self.interface.destroy(self);
    }
}

///Possible states for an event
pub enum EventState {
    ///An event set to "Wait" will cause subsequent wait() calls to block
    ///
    ///This is mostly usefull for manual events as auto events automatically reset to "Wait".
    Wait,
    ///An event set to "Signaled" will unblock threads who are blocks on wait() calls.
    ///
    ///If this is an Auto lock, only one waiting thread will be unblocked as
    ///the state will be automatically set to WAIT after the first threads wakes up.
    Signaled,
}

//TODO : This is super ugly, not sure how to fix though...
cfg_if! {
    if #[cfg(target_os="linux")] {
        enum_from_primitive! {
            #[derive(Debug,Copy,Clone)]
            ///List of available signaling mechanisms on your platform.
            pub enum EventType {
                ///Busy event that automatically resets after a wait
                AutoBusy = 0,
                ///Busy event that needs to be reset manually
                ManualBusy,
                ///Generic event that automatically resets after a wait
                Auto,
                ///Generic event that needs to be reset manually
                Manual,
                ///Linux eventfd event that automatically resets after a wait
                AutoEventFd,
                ///Linux eventfd event that needs to be reset manually
                ManualEventFd,
            }
        }
    } else {
        enum_from_primitive! {
            #[derive(Debug,Copy,Clone)]
            ///List of available signaling mechanisms on your platform.
            pub enum EventType {
                ///Busy event that automatically resets after a wait
                AutoBusy = 0,
                ///Busy event that needs to be reset manually
                ManualBusy,
                ///Generic event that automatically resets after a wait
                Auto,
                ///Generic event that needs to be reset manually
                Manual,
            }
        }
    }
}


///All events implement this trait
#[doc(hidden)]
pub trait EventImpl {
    ///Returns the size of the event structure that will live in shared memory
    fn size_of(&self) -> usize;
    ///Initializes the event
    fn init(&self, event_info: &mut GenericEvent, create_new: bool) -> Result<()>;
    ///De-initializes the event
    fn destroy(&self, event_info: &mut GenericEvent);
    ///This method should only return once the event is signaled
    fn wait(&self, event_ptr: *mut c_void, timeout: Timeout) -> Result<()>;
    ///This method sets the event. This should never block
    fn set(&self, event_ptr: *mut c_void, state: EventState) -> Result<()>;
}

///Provides the ability to set an event to a state
pub trait EventSet {
    ///Set an event to a specific state
    ///
    ///The caller must validate event_index before calling this method
    fn set(&mut self, event_index: usize, state: EventState) -> Result<()>;
}

///Provides the ability to wait on an event
pub trait EventWait {
    ///Wait for an event to become signaled or until timeout is reached
    ///
    ///The caller must validate event_index before calling this method
    fn wait(&self, event_index: usize, timeout: Timeout) -> Result<()>;
}

/* Cross platform Event Implementation */

fn timeout_to_duration(timeout: Timeout) -> Duration {
    Duration::from_millis(
        match timeout {
            Timeout::Infinite => !(0 as u64),
            Timeout::Sec(t) => (t * 1000) as u64,
            Timeout::Milli(t) => (t) as u64,
            Timeout::Micro(t) => (t / 1000) as u64,
            Timeout::Nano(t) => (t / 1000000) as u64,
        }
    )
}

#[doc(hidden)]
pub struct AutoBusy {}
impl EventImpl for AutoBusy {
    fn size_of(&self) -> usize {
        size_of::<AtomicBool>()
    }
    ///Initializes the event
    fn init(&self, event_info: &mut GenericEvent, create_new: bool) -> Result<()> {

        //Nothing to do if we're not the creator
        if !create_new {
            return Ok(());
        }

        let signal: &AtomicBool = unsafe {&mut (*(event_info.ptr as *mut AtomicBool))};
        signal.store(false, Ordering::Relaxed);

        Ok(())
    }
    ///De-initializes the event
    fn destroy(&self, _event_info: &mut GenericEvent) {
        //Nothing to do here
    }
    ///This method should only return once the event is signaled
    fn wait(&self, event_ptr: *mut c_void, timeout: Timeout) -> Result<()> {

        let signal: &AtomicBool = unsafe {&mut (*(event_ptr as *mut AtomicBool))};

        let timeout_len: Duration = match timeout {
            Timeout::Infinite => {
                while !signal.compare_exchange(true, false, Ordering::Relaxed, Ordering::Relaxed).is_ok() {}
                return Ok(())
            },
            _ => timeout_to_duration(timeout),
        };

        //let check_interval = 5;
        //let mut num_attemps: usize = 0;
        let start_time: Instant = Instant::now();

        //Busy loop checking timeout every 5 iterations
        while !signal.compare_exchange(true, false, Ordering::Relaxed, Ordering::Relaxed).is_ok() {
            //num_attemps = num_attemps.wrapping_add(1);
            //if num_attemps%check_interval == 0 {
            if start_time.elapsed() >= timeout_len {
                return Err(From::from("Timed out"));
            }
            //}
        }

        Ok(())
    }
    ///This method sets the event. This should never block
    fn set(&self, event_ptr: *mut c_void, state: EventState) -> Result<()> {
        let signal: &AtomicBool = unsafe {&mut (*(event_ptr as *mut AtomicBool))};

        signal.store(
            match state {
                EventState::Wait => false,
                EventState::Signaled => true,
            },
            Ordering::Relaxed
        );

        Ok(())
    }
}

#[doc(hidden)]
pub struct ManualBusy {}
impl EventImpl for ManualBusy {
    fn size_of(&self) -> usize {
        size_of::<AtomicBool>()
    }
    ///Initializes the event
    fn init(&self, event_info: &mut GenericEvent, create_new: bool) -> Result<()> {

        //Nothing to do if we're not the creator
        if !create_new {
            return Ok(());
        }

        let signal: &AtomicBool = unsafe {&mut (*(event_info.ptr as *mut AtomicBool))};
        signal.store(false, Ordering::Relaxed);

        Ok(())
    }
    ///De-initializes the event
    fn destroy(&self, _event_info: &mut GenericEvent) {
        //Nothing to do here
    }
    ///This method should only return once the event is signaled
    fn wait(&self, event_ptr: *mut c_void, timeout: Timeout) -> Result<()> {

        let signal: &AtomicBool = unsafe {&mut (*(event_ptr as *mut AtomicBool))};

        let timeout_len: Duration = match timeout {
            Timeout::Infinite => {
                while !signal.load(Ordering::Relaxed) {}
                return Ok(())
            },
            _ => timeout_to_duration(timeout),
        };

        //let check_interval = 5;
        //let mut num_attemps: usize = 0;
        let start_time: Instant = Instant::now();

        //Busy loop checking timeout every 5 iterations
        while !signal.load(Ordering::Relaxed) {
            //num_attemps = num_attemps.wrapping_add(1);
            //if num_attemps%check_interval == 0 {
            if start_time.elapsed() >= timeout_len {
                return Err(From::from("Timed out"));
            }
            //}
        }
        Ok(())
    }
    ///This method sets the event. This should never block
    fn set(&self, event_ptr: *mut c_void, state: EventState) -> Result<()> {
        let signal: &AtomicBool = unsafe {&mut (*(event_ptr as *mut AtomicBool))};

        signal.store(
            match state {
                EventState::Wait => false,
                EventState::Signaled => true,
            },
            Ordering::Relaxed
        );

        Ok(())
    }
}