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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
//! An `OpenCL` event.

use std;
use std::ops::{Deref, DerefMut};
use std::convert::Into;
use libc::c_void;
use ffi;
use core::error::{Error as OclError, Result as OclResult};
use core::{self, Event as EventCore, EventInfo, EventInfoResult, ProfilingInfo, ProfilingInfoResult,
    ClEventPtrNew, ClWaitList, EventList as EventListCore, CommandExecutionStatus, EventCallbackFn};

/// An event representing a command or user created event.
#[derive(Clone, Debug)]
pub struct Event(Option<EventCore>);

impl Event {
    /// Creates a new, empty event which must be filled by a newly initiated
    /// command, becoming associated with it.
    pub fn empty() -> Event {
        Event(None)
    }

    /// Creates a new `Event` from a `EventCore`.
    ///
    /// ## Safety
    ///
    /// Not meant to be called directly.
    pub unsafe fn from_core(event_core: EventCore) -> Event {
        Event(Some(event_core))
    }

    /// Waits for all events in list to complete before returning.
    ///
    /// Similar in function to `Queue::finish()`.
    ///
    pub fn wait(&self) -> OclResult<()> {
        assert!(!self.is_empty(), "ocl::Event::wait(): {}", self.err_empty());
        core::wait_for_event(self.0.as_ref().unwrap())
    }

    /// Returns info about the event.
    pub fn info(&self, info_kind: EventInfo) -> EventInfoResult {
        match self.0 {
            Some(ref core) => {
                // match core::get_event_info(core, info_kind) {
                //     Ok(pi) => pi,
                //     Err(err) => EventInfoResult::Error(Box::new(err)),
                // }
                core::get_event_info(core, info_kind)
            },
            None => EventInfoResult::Error(Box::new(self.err_empty())),
        }
    }

    /// Returns info about the event.
    pub fn profiling_info(&self, info_kind: ProfilingInfo) -> ProfilingInfoResult {
        match self.0 {
            Some(ref core) => {
                // match core::get_event_profiling_info(core, info_kind) {
                //     Ok(pi) => pi,
                //     Err(err) => ProfilingInfoResult::Error(Box::new(err)),
                // }
                core::get_event_profiling_info(core, info_kind)
            },
            None => ProfilingInfoResult::Error(Box::new(self.err_empty())),
        }
    }

    /// Returns a reference to the core pointer wrapper, usable by functions in
    /// the `core` module.
    pub fn core_as_ref(&self) -> Option<&EventCore> {
        self.0.as_ref()
    }

    /// Returns a mutable reference to the core pointer wrapper usable by
    /// functions in the `core` module.
    pub fn core_as_mut(&mut self) -> Option<&mut EventCore> {
        self.0.as_mut()
    }

    /// Returns true if this event is 'empty' and has not yet been associated
    /// with a command.
    pub fn is_empty(&self) -> bool {
        self.0.is_none()
    }

    fn err_empty(&self) -> OclError {
        OclError::new("This `ocl::Event` is empty and cannot be used until \
            filled by a command.")
    }

    fn fmt_info(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        f.debug_struct("Event")
            .field("CommandQueue", &self.info(EventInfo::CommandQueue))
            .field("CommandType", &self.info(EventInfo::CommandType))
            .field("ReferenceCount", &self.info(EventInfo::ReferenceCount))
            .field("CommandExecutionStatus", &self.info(EventInfo::CommandExecutionStatus))
            .field("Context", &self.info(EventInfo::Context))
            .finish()
    }
}

impl Into<EventCore> for Event {
    fn into(self) -> EventCore {
        match self.0 {
            Some(evc) => evc,
            None => unsafe { EventCore::null() },
        }
    }
}

impl Into<String> for Event {
    fn into(self) -> String {
        format!("{}", self)
    }
}

impl std::fmt::Display for Event {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        self.fmt_info(f)
    }
}

impl AsRef<EventCore> for Event {
    fn as_ref(&self) -> &EventCore {
        self.0.as_ref().ok_or(self.err_empty()).expect("ocl::Event::as_ref()")
    }
}

impl Deref for Event {
    type Target = EventCore;

    fn deref(&self) -> &EventCore {
        self.0.as_ref().ok_or(self.err_empty()).expect("ocl::Event::deref()")
    }
}

impl DerefMut for Event {
    fn deref_mut(&mut self) -> &mut EventCore {
        assert!(!self.is_empty(), "ocl::Event::deref_mut(): {}", self.err_empty());
        self.0.as_mut().unwrap()
    }
}

unsafe impl ClEventPtrNew for Event {
    fn ptr_mut_ptr_new(&mut self) -> OclResult<*mut ffi::cl_event> {
        if !self.is_empty() {
            return OclError::err("ocl::Event: Attempting to use a non-empty event as a new event
                is not allowed. Please create a new, empty, event with ocl::Event::empty().");
        }

        unsafe {
            self.0 = Some(EventCore::null());
            Ok(self.0.as_mut().unwrap().as_ptr_mut())
        }
    }
}

unsafe impl<'a> ClEventPtrNew for &'a mut Event {
    fn ptr_mut_ptr_new(&mut self) -> OclResult<*mut ffi::cl_event> {
        if !self.is_empty() {
            return OclError::err("ocl::Event: Attempting to use a non-empty event as a new event
                is not allowed. Please create a new, empty, event with ocl::Event::empty().");
        }

        unsafe {
            self.0 = Some(EventCore::null());
            Ok(self.0.as_mut().unwrap().as_ptr_mut())
        }
    }
}

unsafe impl ClWaitList for Event {
    unsafe fn as_ptr_ptr(&self) -> *const ffi::cl_event {
        // self.0.as_ref().ok_or(self.err_empty()).expect("ocl::Event::as_ref()").as_ptr_ptr()
        match self.0 {
            Some(ref ec) => ec.as_ptr_ptr(),
            None => 0 as *const ffi::cl_event,
        }
    }

    fn count(&self) -> u32 {
        match self.0 {
            Some(ref ec) => ec.count(),
            None => 0,
        }
    }
}



/// A list of events for coordinating enqueued commands.
///
/// Events contain status information about the command that
/// created them. Used to coordinate the activity of multiple commands with
/// more fine-grained control than the queue alone.
///
/// For access to individual events use `get_clone` and `last_clone` then
/// either store or discard the result.
///
// [FIXME] TODO: impl Index.
#[derive(Debug, Clone)]
pub struct EventList {
    event_list_core: EventListCore,
}

impl EventList {
    /// Returns a new, empty, `EventList`.
    pub fn new() -> EventList {
        EventList {
            event_list_core: EventListCore::new(),
        }
    }

    /// Adds an event to the list.
    pub fn push(&mut self, event: Event) {
        self.event_list_core.push(event.into());
    }

    /// Removes the last event from the list and returns it.
    pub fn pop(&mut self) -> Option<Event> {
        match self.event_list_core.pop() {
            Some(ev_res) => {
                match ev_res {
                    Ok(ev) => unsafe { Some(Event::from_core(ev)) },
                    Err(_) => None,
                }
            },
            None => None,
        }
    }

    // /// Appends a new null element to the end of the list and returns...
    // /// [FIXME]: Update
    // pub fn allot(&mut self) -> &mut Event {
    //     unsafe { self.event_list_core.push(EventCore::null()); }
    //     self.event_list_core.last_mut().unwrap()
    // }

    /// Returns a new copy of an event by index.
    pub fn get_clone(&self, index: usize) -> Option<Event> {
        match self.event_list_core.get_clone(index) {
            Some(ev_res) => {
                match ev_res {
                    Ok(ev) => unsafe { Some(Event::from_core(ev)) },
                    Err(_) => None,
                }
            },
            None => None,
        }
    }

    /// Returns a copy of the last event in the list.
    pub fn last_clone(&self) -> Option<Event> {
        match self.event_list_core.last_clone() {
            Some(ev_res) => {
                match ev_res {
                    Ok(ev) => unsafe { Some(Event::from_core(ev)) },
                    Err(_) => None,
                }
            },
            None => None,
        }
    }

    /// Sets a callback function, `callback_receiver`, to trigger upon completion of
    /// the *last event* added to the event list with an optional reference to user
    /// data.
    ///
    /// # Safety
    ///
    /// `user_data` must be guaranteed to still exist if and when `callback_receiver`
    /// is ever called.
    ///
    /// TODO: Create a safer type wrapper for `callback_receiver`.
    /// TODO: Move this method to `Event`.
    pub unsafe fn set_callback<T>(&self,
                callback_receiver: Option<EventCallbackFn>,
                user_data: &mut T,
                ) -> OclResult<()>
    {
        let event_core = try!(try!(self.event_list_core.last_clone().ok_or(
            OclError::new("ocl::EventList::set_callback: This event list is empty."))));

        core::set_event_callback(&event_core, CommandExecutionStatus::Complete,
                    callback_receiver, user_data as *mut _ as *mut c_void)
    }

    // pub fn clear_completed(&mut self) -> OclResult<()> {
    //     self.event_list_core.clear_completed()
    // }

    /// Returns the number of events in the list.
    pub fn len(&self) -> usize {
        self.event_list_core.len()
    }

    /// Returns if there is no events.
    pub fn is_empty(&self) -> bool {
        self.event_list_core.len() == 0
    }

    // Returns a reference to the underlying `core` event list.
    pub fn core_as_ref(&self) -> &EventListCore {
        &self.event_list_core
    }

    // Returns a mutable reference to the underlying `core` event list.
    pub fn core_as_mut(&mut self) -> &mut EventListCore {
        &mut self.event_list_core
    }

    /// Waits for all events in list to complete.
    pub fn wait(&self) -> OclResult<()> {
        if !self.event_list_core.is_empty() {
            core::wait_for_events(self.event_list_core.count(), &self.event_list_core)
        } else {
            Ok(())
        }
    }
}

impl AsRef<EventListCore> for EventList {
    fn as_ref(&self) -> &EventListCore {
        &self.event_list_core
    }
}

impl Deref for EventList {
    type Target = EventListCore;

    fn deref(&self) -> &EventListCore {
        &self.event_list_core
    }
}

impl DerefMut for EventList {
    fn deref_mut(&mut self) -> &mut EventListCore {
        &mut self.event_list_core
    }
}

unsafe impl ClEventPtrNew for EventList {
    fn ptr_mut_ptr_new(&mut self) -> OclResult<*mut ffi::cl_event> {
        Ok(self.event_list_core.allot())
    }
}

unsafe impl<'a> ClEventPtrNew for &'a mut EventList {
    fn ptr_mut_ptr_new(&mut self) -> OclResult<*mut ffi::cl_event> {
        Ok(self.event_list_core.allot())
    }
}

unsafe impl ClWaitList for EventList {
    unsafe fn as_ptr_ptr(&self) -> *const ffi::cl_event {
        self.event_list_core.as_ptr_ptr()
    }

    fn count(&self) -> u32 {
        self.event_list_core.count()
    }
}