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
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
//! An OpenCL event.
//!
//
// ### Notes
//
// * `EventArray` (a stack allocated event list with a maximum length of 8,
//   akin to `RawEventArray`) is incomplete (TODO: Complete it).
// * It's not yet clear whether or not to keep EventArray and EventList
//   separate or to combine them into a smart-list that might be either one
//   depending on the circumstances.
// * It would be nice to have a "master" list type but it doesn't look like
//   that's particularly feasable (although ClWaitListPtrEnum basically serves
//   that role as long as lifetimes aren't an issue).
//

extern crate nodrop;

use std::{mem, ptr, fmt};
use std::borrow::Borrow;
use std::ops::{Deref, DerefMut};
use std::cell::Ref;
use futures::{Future, Poll, Async};
#[cfg(not(feature = "async_block"))]
use futures::task;
use ffi::cl_event;
use core::{self, Event as EventCore, EventInfo, EventInfoResult, ProfilingInfo,
    ProfilingInfoResult, ClNullEventPtr, ClWaitListPtr, ClEventPtrRef,
    CommandQueue as CommandQueueCore, ClContextPtr};
use core::error::{Error as OclError, Result as OclResult};
use standard::{Queue, ClWaitListPtrEnum};
#[cfg(not(feature = "async_block"))]
use standard::{_unpark_task, box_raw_void};
use self::nodrop::NoDrop;

const PRINT_DEBUG: bool = false;

/// An event representing a command or user created event.
///
#[derive(Clone, Debug)]
#[repr(C)]
#[must_use = "futures do nothing unless polled"]
pub struct Event(EventCore);

impl Event {
    /// Creates a new, empty (null) event which must be filled by a command,
    /// associating the event with it.
    pub fn empty() -> Event {
        Event(EventCore::null())
    }

    /// Creates a new, empty event which must be filled by a newly initiated
    /// command, associating the event with it.
    pub fn user<C: ClContextPtr>(context: C) -> OclResult<Event> {
        EventCore::user(context).map(Event)
    }

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

    /// Sets a callback function to trigger upon completion of this event
    /// which will unpark the current task.
    ///
    /// To be used within the context of a futures task.
    ///
    /// ## Panics
    ///
    /// This function will panic if a task is not currently being executed.
    /// That is, this method can be dangerous to call outside of an
    /// implementation of poll.
    #[cfg(not(feature = "async_block"))]
    pub fn set_unpark_callback(&self) -> OclResult<()> {
        let task_ptr = box_raw_void(task::current());
        unsafe { self.set_callback(_unpark_task, task_ptr) }
    }

    /// Returns info about the event.
    pub fn info(&self, info_kind: EventInfo) -> EventInfoResult {
        core::get_event_info(&self.0, info_kind)
    }

    /// Returns info about the event.
    pub fn profiling_info(&self, info_kind: ProfilingInfo) -> ProfilingInfoResult {
        core::get_event_profiling_info(&self.0, info_kind)
    }

    /// Returns this event's associated command queue.
    pub fn queue_core(&self) -> OclResult<CommandQueueCore> {
        match self.info(EventInfo::CommandQueue) {
            EventInfoResult::CommandQueue(queue_core) => Ok(queue_core),
            EventInfoResult::Error(err) => Err(*err),
            _ => unreachable!(),
        }
    }

    /// Returns a reference to the core pointer wrapper, usable by functions in
    /// the `core` module.
    ///
    #[inline]
    pub fn core(&self) -> &EventCore {
        &self.0
    }

    /// Consumes the `Event`, returning the wrapped `cl_event` pointer.
    ///
    /// To avoid a memory leak the pointer must be converted back to an `Event` using
    /// [`Event::from_raw`][from_raw].
    ///
    /// [from_raw]: struct.Event.html#method.from_raw
    ///
    #[inline]
    pub fn into_raw(self) -> cl_event {
        self.0.into_raw()
    }

    /// Constructs an `Event` from a raw `cl_event` pointer.
    ///
    /// The raw pointer must have been previously returned by a call to a
    /// [`Event::into_raw`][into_raw].
    ///
    /// [into_raw]: struct.Event.html#method.into_raw
    #[inline]
    pub unsafe fn from_raw(ptr: cl_event) -> Event {
        EventCore::from_raw(ptr).into()
    }

    fn fmt_info(&self, f: &mut fmt::Formatter) -> 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()
    }

    #[inline]
    fn _count(&self) -> u32 {
        if self.0.is_null() { 0 } else { 1 }
    }
}

impl From<EventCore> for Event {
    #[inline]
    fn from(ev: EventCore) -> Event {
        if ev.is_valid() {
            Event(ev)
        } else {
            panic!("ocl::Event::from::<EventCore>: Invalid event.");
        }
    }
}

impl From<Event> for EventCore {
    #[inline]
    fn from(ev: Event) -> EventCore {
        if ev.is_valid() {
            ev.0
        } else {
            panic!("ocl::EventCore::from::<Event>: Invalid event.");
        }
    }
}

impl Default for Event {
    fn default() -> Event {
        Event::empty()
    }
}

impl Deref for Event {
    type Target = EventCore;

    fn deref(&self) -> &EventCore {
        &self.0
    }
}

impl DerefMut for Event {
    fn deref_mut(&mut self) -> &mut EventCore {
        &mut self.0
    }
}

impl AsRef<EventCore> for Event {
    fn as_ref(&self) -> &EventCore {
        &self.0
    }
}


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

unsafe impl<'e> ClEventPtrRef<'e> for Event {
    unsafe fn as_ptr_ref(&'e self) -> &'e cl_event {
        self.0.as_ptr_ref()
    }
}

unsafe impl<'a> ClNullEventPtr for &'a mut Event {
    #[inline] fn alloc_new(&mut self) -> *mut cl_event { (&mut self.0).alloc_new() }

    #[inline] unsafe fn clone_from<E: AsRef<EventCore>>(&mut self, ev: E) {
        self.0.clone_from(ev.as_ref())
    }
}

unsafe impl ClWaitListPtr for Event {
    #[inline] unsafe fn as_ptr_ptr(&self) -> *const cl_event { self.0.as_ptr_ptr() }
    #[inline] fn count(&self) -> u32 { self._count() }
}

unsafe impl<'a> ClWaitListPtr for  &'a Event {
    #[inline] unsafe fn as_ptr_ptr(&self) -> *const cl_event { self.0.as_ptr_ptr() }
    #[inline] fn count(&self) -> u32 { self._count() }
}

impl Future for Event {
    type Item = ();
    type Error = OclError;

    // Non-blocking, proper implementation.
    //
    // * NOTE: There is currently no check to ensure that only one callback is
    //   created (is this ok?).
    //   - TODO: Look into possible effects of unparking a task multiple times.
    //
    #[cfg(not(feature = "async_block"))]
    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        debug_assert!(self.0.is_valid());

        match self.is_complete() {
            Ok(true) => {
                Ok(Async::Ready(()))
            }
            Ok(false) => {
                self.set_unpark_callback()?;
                Ok(Async::NotReady)
            },
            Err(err) => Err(err),
        }
    }

    // Blocking implementation (yuk).
    #[cfg(feature = "async_block")]
    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        debug_assert!(self.0.is_valid());
        self.wait_for()?;
        Ok(Async::Ready(()))
    }
}



/// Returns an empty, initialized (zeroed) event array.
fn empty_event_array() -> NoDrop<[Event; 8]> {
    let mut array: [Event; 8];
    unsafe {
        array = mem::uninitialized();
        for elem in &mut array[..] {
            ptr::write(elem, Event::empty());
        }
    }
    NoDrop::new(array)
}


/// Swaps an event with a new empty (null) event and returns it.
fn take(event: &mut Event) -> Event {
    let mut eold = Event::empty();
    mem::swap(event, &mut eold);
    eold
}


/// 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.
///
///
/// [NOTE]: Unstable and minimally tested.
//
// * [FIXME] TODO: impl Index.
// #[derive(Debug)]
pub struct EventArray {
    array: NoDrop<[Event; 8]>,
    len: usize,
}

impl EventArray {
    /// Returns a new, empty, `EventArray`.
    pub fn new() -> EventArray {
        EventArray {
            array: empty_event_array(),
            len: 0,
        }
    }

    /// Pushes a new event into the list.
    pub fn push<E: Into<Event>>(&mut self, event: E) -> Result<(), Event> {
        if (self.len) < self.array.len() {
            let event = event.into();
            debug_assert!(self.array[self.len].is_empty());
            self.array[self.len] = event;
            self.len += 1;
            Ok(())
        } else {
            Err(event.into())
        }
    }

    /// Pushes an `Option<Event>` to the list if it is `Some(...)`.
    pub fn push_some<E: Into<Event>>(&mut self, event: Option<E>) -> Result<(), Event> {
        if let Some(e) = event {
            self.push(e.into())
        } else {
            Ok(())
        }
    }

    /// Removes the last event from the list and returns it.
    pub fn pop(&mut self) -> Option<Event> {
        if self.len > 0 {
            self.len -= 1;
            Some(take(&mut self.array[self.len]))
        } else {
            None
        }
    }

    /// Removes an event from the list and returns it, swapping the last element into its place.
    pub fn swap_remove(&mut self, idx: usize) -> Event {
        assert!(idx < self.len);
        let old = take(&mut self.array[idx]);
        let src_ptr = &mut self.array[self.len - 1] as *mut Event;
        let dst_ptr = &mut self.array[idx] as *mut Event;
        unsafe { ptr::swap(src_ptr, dst_ptr); }
        self.len -= 1;
        old
    }

    /// Removes an event from the list and returns it, shifting elements after it to the left.
    ///
    /// [MAY DEPRICATE]: Prefer `::swap_remove`, this function is really unnecessary.
    pub fn remove(&mut self, idx: usize) -> Event {
        assert!(idx < self.len);
        let old = take(&mut self.array[idx]);

        // Shift everything after `idx` to the left:
        unsafe {
            let ptr = self.array.as_mut_ptr().offset(idx as isize);
            ptr::copy(ptr.offset(1), ptr, self.len - idx - 1);
        }
        self.len -= 1;
        old
    }

    /// Clears all events from the list whether or not they have completed.
    ///
    /// Forwards any errors related to releasing events.
    ///
    #[inline]
    pub fn clear(&mut self) {
        for ev in &mut self.array[..self.len] {
            let _ = take(ev);
        }
        self.len = 0;
    }

    /// Clears events which have already completed.
    pub fn clear_completed(&mut self) -> OclResult<()> {
        let mut new_len = 0;

        for idx in 0..self.len {
            if self.array[idx].is_complete()? {
                let _ = take(&mut self.array[idx]);
            } else {
                let dst_ptr = &mut self.array[new_len] as *mut Event;
                unsafe { ptr::swap(&mut self.array[idx], dst_ptr); }
                new_len += 1;
            }
        }

        self.len = new_len;
        Ok(())
    }

    /// Blocks the host thread until all events in this list are complete.
    pub fn wait_for(&self) -> OclResult<()> {
        for ev in &self.array[..self.len] {
            ev.wait_for()?;
        }
        Ok(())
    }

    /// Enqueue a marker event representing the completion of each and every
    /// event in this list.
    pub fn enqueue_marker(&self, queue: &Queue) -> OclResult<Event> {
        if self.array.is_empty() { return Err("EventArray::enqueue_marker: List empty.".into()); }
        queue.enqueue_marker(Some(self))
    }

    /// The number of events in this list.
    #[inline]
    pub fn len(&self) -> usize {
        self.len
    }

    /// Returns a slice of events in the list.
    #[inline]
    pub fn as_slice(&self) -> &[Event] {
        &self.array[..self.len]
    }

    /// Returns a mutable slice of events in the list.
    #[inline]
    pub fn as_mut_slice(&mut self) -> &mut [Event] {
        &mut self.array[..self.len]
    }

    #[inline]
    fn _alloc_new(&mut self) -> Result<*mut cl_event, &'static str> {
        match self.push(Event::empty()) {
            Ok(_) => Ok((&mut self.array[self.len - 1]) as *mut _ as *mut cl_event),
            Err(_) => Err("EventArray::_alloc_new: Error attempting to add a new event \
                to the event list: this list is full"),
        }
    }

    #[inline]
    unsafe fn _as_ptr_ptr(&self) -> *const cl_event {
        if self.len > 0 {
            &self.array[0] as *const _ as *const cl_event
        } else {
            0 as *const cl_event
        }
    }

    #[inline]
    fn _count(&self) -> u32 {
        self.len as u32
    }
}

impl<'a, E> From<E> for EventArray where E: Into<Event> {
    fn from(event: E) -> EventArray {
        let mut array = empty_event_array();
        array[0] = event.into();

        EventArray {
            array: array,
            len: 1,
        }
    }
}

impl<'a, E> From<&'a E> for EventArray where E: Into<Event> + Clone {
    #[inline]
    fn from(event: &E) -> EventArray {
        Self::from(event.clone().into())
    }
}

impl<'a, E> From<&'a [E]> for EventArray where E: Into<Event> + Clone {
    fn from(events: &[E]) -> EventArray {
        let mut array = empty_event_array();

        for (idx, event) in events.iter().enumerate() {
            array[idx] = event.clone().into();
        }

        EventArray {
            array: array,
            len: events.len(),
        }
    }
}

impl Deref for EventArray {
    type Target = [Event];

    #[inline]
    fn deref(&self) -> &[Event] {
        self.as_slice()
    }
}

impl DerefMut for EventArray {
    #[inline]
    fn deref_mut(&mut self) -> &mut [Event] {
        self.as_mut_slice()
    }
}

impl Clone for EventArray {
    fn clone(&self) -> EventArray {
        let mut new_a = empty_event_array();
        for i in 0..self.len {
            new_a[i] = self.array[i].clone();
        }
        EventArray { array: new_a, len: self.len }
    }
}

impl Drop for EventArray {
    fn drop(&mut self) {
        // ptr::drop_in_place(self.as_mut_slice());
        self.clear();

        for idx in 0..self.array.len() {
            debug_assert!(self.array[idx].is_empty());
        }
    }
}

impl fmt::Debug for EventArray {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "EventArray {{ array: {:?}, len: {} }}", &self.array[..], self.len)
    }
}

impl Future for EventArray {
    type Item = ();
    type Error = OclError;

    /// Removes (pops) each event from this list and waits for it to complete,
    /// dropping it in the process.
    //
    // * See `EventList::poll` for notes.
    #[cfg(not(feature = "async_block"))]
    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        while let Some(event) = self.pop() {
            if !event.is_complete()? {
                event.set_unpark_callback()?;
                return Ok(Async::NotReady);
            }
        }
        Ok(Async::Ready(()))
    }

    /// Removes (pops) each event from this list and waits for it to complete,
    /// dropping it in the process.
    #[cfg(feature = "async_block")]
    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        while let Some(event) = self.pop() {
            event.wait_for()?;
        }
        Ok(Async::Ready(()))
    }
}

unsafe impl<'a> ClNullEventPtr for &'a mut EventArray {
    #[inline] fn alloc_new(&mut self) -> *mut cl_event {
        self._alloc_new().expect("<EventArray as ClNullEventPtr>::alloc_new")
    }

    #[inline] unsafe fn clone_from<E: AsRef<EventCore>>(&mut self, ev: E) {
        assert!(ev.as_ref().is_valid());
        *self._alloc_new().expect("<EventArray as ClNullEventPtr>::clone_from") =
            ev.as_ref().clone().into_raw()
    }
}

unsafe impl ClWaitListPtr for EventArray {
    #[inline] unsafe fn as_ptr_ptr(&self) -> *const cl_event { self._as_ptr_ptr() }
    #[inline] fn count(&self) -> u32 { self._count() }
}

unsafe impl<'a> ClWaitListPtr for &'a EventArray {
    #[inline] unsafe fn as_ptr_ptr(&self) -> *const cl_event { self._as_ptr_ptr() }
    #[inline] fn count(&self) -> u32 { self._count() }
}



/// The guts of an EventList.
#[derive(Debug, Clone)]
enum Inner {
    Array(EventArray),
    Vec(Vec<Event>),
}


/// 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.
///
/// `EventList` is a dynamically allocated list. It will be (internally) stack
/// allocated (as an `[Event; 8]`) until it reaches a length of 9 at which
/// time it will become heap-allocated (a `Vec<Event>`).
///
/// At the time of this writing, converting back from heap to stack allocation
/// is not implemented but a bit of prodding (by filing an issue) would
/// probably work to remedy that if anyone thinks it useful.
///
// * [FIXME] TODO: impl Index.
#[derive(Debug, Clone)]
pub struct EventList {
    inner: Inner,
}

impl EventList {
    /// Returns a new, empty, stack-allocated `EventList`.
    #[inline]
    pub fn new() -> EventList {
        EventList {
            inner: Inner::Array(EventArray::new()),
            // inner: Inner::Vec(Vec::new()),
        }
    }

    /// Returns a new, empty, EventList` with an initial capacity of `cap`.
    ///
    /// If `cap` is greater than 8, the event list will be heap-allocated.
    #[inline]
    pub fn with_capacity(cap: usize) -> EventList {
        if cap <= 8 {
            EventList { inner: Inner::Array(EventArray::new()) }
        } else {
            EventList { inner: Inner::Vec(Vec::with_capacity(cap)) }
        }
    }

    /// Converts the contained list from a stack allocated to a heap allocated
    /// array [or vice-versa].
    ///
    /// FIXME: Implement conversion from Vec -> array.
    fn convert(&mut self) {
        let new_inner: Inner;

        match self.inner {
            Inner::Array(ref a) => {
                let vec = a.as_slice().to_owned();
                new_inner = Inner::Vec(vec);
            },
            Inner::Vec(ref _v) => unimplemented!(),
        }

        self.inner = new_inner;
    }

    /// Adds an event to the list.
    //
    // TODO: Clean this up. There must be a simpler way to do this.
    #[inline]
    pub fn push<E: Into<Event>>(&mut self, event: E) {
        let mut event: Option<Event> = Some(event.into());

        match self.inner {
            Inner::Array(ref mut a) => if let Some(ev) = event {
                match a.push(ev) {
                    Ok(_) => return,
                    Err(ev) => event = Some(ev),
                }
            },
            Inner::Vec(ref mut v) => {
                if let Some(ev) = event { v.push(ev); }
                return;
            },
        }

        if let Some(ev) = event {
            self.convert();
            self.push(ev);
        }
    }

    /// Pushes an `Option<Event>` to the list if it is `Some(...)`.
    #[inline]
    pub fn push_some<E: Into<Event>>(&mut self, event: Option<E>) {
        if let Some(e) = event { self.push(e.into()) }
    }

    /// Removes the last event from the list and returns it.
    #[inline]
    pub fn pop(&mut self) -> Option<Event> {
        match self.inner {
            Inner::Array(ref mut a) => a.pop(),
            Inner::Vec(ref mut v) => v.pop(),
        }
    }

    /// Clears all events from the list whether or not they have completed.
    ///
    /// Forwards any errors related to releasing events.
    ///
    #[inline]
    pub fn clear(&mut self) {
        match self.inner {
            Inner::Array(ref mut a) => a.clear(),
            Inner::Vec(ref mut v) => v.clear(),
        }
    }

    /// Clears events which have completed.
    pub fn clear_completed(&mut self) -> OclResult<()> {
        match self.inner {
            Inner::Array(ref mut a) => a.clear_completed(),
            Inner::Vec(ref mut v) => {
                // * TODO: Reimplement optimized version using
                //   `util::vec_remove_rebuild` (from old `EventListCore`).
                let mut events = Vec::with_capacity(v.capacity());
                mem::swap(&mut events, v);
                for event in events {
                    if !event.is_complete()? {
                        v.push(event);
                    }
                }
                Ok(())
            },
        }
    }

    /// Blocks the host thread until all events in this list are complete.
    pub fn wait_for(&self) -> OclResult<()> {
        match self.inner {
            Inner::Array(ref a) => a.wait_for(),
            Inner::Vec(ref v) => {
                for event in v.iter() {
                    event.wait_for()?;
                }
                Ok(())
            },
        }
    }

    /// Enqueue a marker event representing the completion of each and every
    /// event in this list.
    ///
    /// ### Platform Compatibility
    ///
    /// Some device/platform combinations (particularly older Intel CPUs on
    /// Intel platform drivers) may have intermittent issues waiting on
    /// markers when multiple threads are in use. This is rare and can be
    /// circumvented by using AMD platform drivers instead. Please file an
    /// issue immediately if you run into problems on your platform so that we
    /// may make note of it here in the documentation.
    pub fn enqueue_marker(&self, queue: &Queue) -> OclResult<Event> {
        match self.inner {
            Inner::Array(ref a) => a.enqueue_marker(queue),
            Inner::Vec(ref v) => {
                if v.is_empty() { return Err("EventList::enqueue_marker: List empty.".into()); }
                queue.enqueue_marker(Some(self))
            },
        }
    }

    /// Returns a slice of the contained events.
    #[inline]
    pub fn as_slice(&self) -> &[Event] {
        match self.inner {
            Inner::Array(ref a) => a.as_slice(),
            Inner::Vec(ref v) => v.as_slice(),
        }
    }

    /// Returns a mutable slice of the contained events.
    #[inline]
    pub fn as_mut_slice(&mut self) -> &mut [Event] {
        match self.inner {
            Inner::Array(ref mut a) => a.as_mut_slice(),
            Inner::Vec(ref mut v) => v.as_mut_slice(),
        }
    }

    #[inline]
    fn _alloc_new(&mut self) -> *mut cl_event {
        match self.inner {
            Inner::Array(ref mut a) => {
                match a._alloc_new() {
                    Ok(ptr) => return ptr,
                    Err(_) => (),
                }
            },
            Inner::Vec(ref mut v) => {
                v.push(Event::empty());
                return v.last_mut().unwrap() as *mut _ as *mut cl_event;
            },
        }

        self.convert();
        self._alloc_new()
    }

    #[inline]
    unsafe fn _as_ptr_ptr(&self) -> *const cl_event {
        match self.inner {
            Inner::Array(ref a) => a._as_ptr_ptr(),
            Inner::Vec(ref v) => {
                match v.first() {
                    Some(ev) => ev as *const _ as *const cl_event,
                    None => 0 as *const cl_event,
                }
            },
        }
    }

    #[inline]
    fn _count(&self) -> u32 {
        match self.inner {
            Inner::Array(ref a) => a._count(),
            Inner::Vec(ref v) => v.len() as u32,
        }
    }
}

impl<'a, E> From<E> for EventList where E: Into<Event> {
    #[inline]
    fn from(event: E) -> EventList {
        EventList { inner: Inner::Array(EventArray::from(event)) }
    }
}

impl<'a, E> From<&'a E> for EventList where E: Into<Event> + Clone {
    #[inline]
    fn from(event: &E) -> EventList {
        EventList { inner: Inner::Array(EventArray::from(event)) }
    }
}

impl<'a> From<Vec<Event>> for EventList {
    #[inline]
    fn from(events: Vec<Event>) -> EventList {
        EventList { inner: Inner::Vec(events) }
    }
}

impl<'a, E> From<&'a Option<E>> for EventList where E: Into<Event> + Clone {
    fn from(event: &Option<E>) -> EventList {
        let mut el = EventList::new();
        if let Some(ref e) = *event { el.push(e.clone().into()) }
        el
    }
}

impl<'a, 'b, E> From<Option<&'b E>> for EventList where 'b: 'a, E: Into<Event> + Clone {
    fn from(event: Option<&E>) -> EventList {
        let mut el = EventList::new();
        if let Some(e) = event { el.push(e.clone().into()) }
        el
    }
}

impl<'a, 'b, E> From<&'a Option<&'b E>> for EventList where 'b: 'a, E: Into<Event> + Clone {
    fn from(event: &Option<&E>) -> EventList {
        let mut el = EventList::new();
        if let Some(e) = *event { el.push(e.clone().into()) }
        el
    }
}

impl<'a, E> From<&'a [E]> for EventList where E: Into<Event> + Clone {
    fn from(events: &[E]) -> EventList {
        if events.len() <= 8 {
            EventList { inner: Inner::Array(EventArray::from(events)) }
        } else {
            EventList { inner: Inner::Vec(events.iter().map(|e| e.clone().into()).collect()) }
        }
    }
}

impl<'a, E> From<&'a [Option<E>]> for EventList where E: Into<Event> + Clone {
    fn from(events: &[Option<E>]) -> EventList {
        let mut el = EventList::with_capacity(events.len());

        for event in events {
            if let Some(ref e) = *event { el.push(e.clone().into()) }
        }
        el
    }
}

impl<'a, 'b, E> From<&'a [Option<&'b E>]> for EventList where 'b: 'a, E: Into<Event> + Clone {
    fn from(events: &[Option<&E>]) -> EventList {
        let mut el = EventList::with_capacity(events.len());

        for event in events {
            if let Some(e) = *event { el.push(e.clone().into()) }
        }
        el
    }
}

impl<'a, 'b, E> From<&'a [&'b Option<E>]> for EventList where 'b: 'a, E: Into<Event> + Clone {
    fn from(events: &[&Option<E>]) -> EventList {
        let mut el = EventList::with_capacity(events.len());

        for event in events {
            if let Some(ref e) = **event { el.push(e.clone().into()) }
        }
        el
    }
}

impl<'a, 'b, 'c, E> From<&'a [&'b Option<&'c E>]> for EventList
        where 'c: 'b, 'b: 'a, E: Into<Event> + Clone
{
    fn from(events: &[&Option<&E>]) -> EventList {
        let mut el = EventList::with_capacity(events.len());

        for event in events {
            if let Some(e) = **event { el.push(e.clone().into()) }
        }
        el
    }
}

macro_rules! impl_event_list_from_arrays {
    ($( $len:expr ),*) => ($(
        impl<'e, E> From<[E; $len]> for EventList where E: Into<Event> {
            fn from(events: [E; $len]) -> EventList {
                let mut el = EventList::with_capacity(events.len());
                for idx in 0..events.len() {
                    let event = unsafe { ptr::read(events.get_unchecked(idx)) };
                    el.push(event.into());
                }
                // Ownership has been unsafely transfered to the new event
                // list without modifying the event reference count. Not
                // forgetting the source array would cause a double drop.
                mem::forget(events);
                el
            }
        }

        impl<'e, E> From<[Option<E>; $len]> for EventList where E: Into<Event> {
            fn from(events: [Option<E>; $len]) -> EventList {
                let mut el = EventList::with_capacity(events.len());
                for idx in 0..events.len() {
                    let event_opt = unsafe { ptr::read(events.get_unchecked(idx)) };
                    if let Some(event) = event_opt { el.push(event.into()); }
                }
                mem::forget(events);
                el
            }
        }

        impl<'e, E> From<[Option<&'e E>; $len]> for EventList where E: Into<Event> + Clone {
            fn from(events: [Option<&E>; $len]) -> EventList {
                let mut el = EventList::with_capacity(events.len());
                for idx in 0..events.len() {
                    let event_opt = unsafe { ptr::read(events.get_unchecked(idx)) };
                    if let Some(event) = event_opt { el.push(event.clone().into()); }
                }
                mem::forget(events);
                el
            }
        }

        impl<'e, 'f, E> From<[&'f Option<E>; $len]> for EventList where 'e: 'f, E: Into<Event> + Clone {
            fn from(events: [&'f Option<E>; $len]) -> EventList {
                let mut el = EventList::with_capacity(events.len());
                for idx in 0..events.len() {
                    let event_opt = unsafe { ptr::read(events.get_unchecked(idx)) };
                    if let Some(ref event) = *event_opt { el.push(event.clone().into()); }
                }
                mem::forget(events);
                el
            }
        }

        impl<'e, 'f, E> From<[&'f Option<&'e E>; $len]> for EventList where 'e: 'f, E: Into<Event> + Clone {
            fn from(events: [&'f Option<&'e E>; $len]) -> EventList {
                let mut el = EventList::with_capacity(events.len());
                for idx in 0..events.len() {
                    let event_opt = unsafe { ptr::read(events.get_unchecked(idx)) };
                    if let Some(event) = *event_opt { el.push(event.clone().into()); }
                }
                mem::forget(events);
                el
            }
        }
    )*);
}

impl_event_list_from_arrays!(1, 2, 3, 4, 5, 6, 7, 8);

impl<'a> From<&'a [cl_event]> for EventList {
    fn from(raw_events: &[cl_event]) -> EventList {
        let mut event_list = EventList::new();
        for &ptr in raw_events {
            let event_core = unsafe { EventCore::from_raw_copied_ptr(ptr).expect(
                "EventList::from: Error converting from raw 'cl_event'") };
            event_list.push(event_core);
        }
        event_list
    }
}

impl<'a> From<EventArray> for EventList {
    #[inline]
    fn from(events: EventArray) -> EventList {
        EventList { inner: Inner::Array(events) }
    }
}

impl<'a> From<RawEventArray> for EventList {
    #[inline]
    fn from(raw_events: RawEventArray) -> EventList {
        EventList::from(raw_events.as_slice())
    }
}

impl<'a> From<Box<ClWaitListPtr>> for EventList {
    fn from(trait_obj: Box<ClWaitListPtr>) -> EventList {
        let raw_slice = unsafe {
            ::std::slice::from_raw_parts(trait_obj.as_ptr_ptr(), trait_obj.count() as usize)
        };

        Self::from(raw_slice)
    }
}

impl<'a> From<&'a Box<ClWaitListPtr>> for EventList {
    fn from(trait_obj: &Box<ClWaitListPtr>) -> EventList {
        let raw_slice = unsafe {
            ::std::slice::from_raw_parts(trait_obj.as_ptr_ptr(), trait_obj.count() as usize)
        };

        Self::from(raw_slice)
    }
}

impl<'a> From<Ref<'a, ClWaitListPtr>> for EventList {
    fn from(trait_obj: Ref<'a, ClWaitListPtr>) -> EventList {
        let raw_slice = unsafe {
            ::std::slice::from_raw_parts(trait_obj.as_ptr_ptr(), trait_obj.count() as usize)
        };

        Self::from(raw_slice)
    }
}

impl<'a> From<ClWaitListPtrEnum<'a>> for EventList {
    /// Returns an `EventList` containing owned copies of each element in
    /// this `ClWaitListPtrEnum`.
    fn from(wlpe: ClWaitListPtrEnum<'a>) -> EventList {
        match wlpe {
            ClWaitListPtrEnum::Null => EventList::with_capacity(0),
            ClWaitListPtrEnum::RawEventArray(e) => e.as_slice().into(),
            ClWaitListPtrEnum::EventCoreOwned(e) => EventList::from(vec![e.into()]),
            ClWaitListPtrEnum::EventOwned(e) => EventList::from(vec![e.into()]),
            ClWaitListPtrEnum::EventCore(e) => EventList::from(vec![e.clone().into()]),
            ClWaitListPtrEnum::Event(e) => EventList::from(vec![e.clone().into()]),
            ClWaitListPtrEnum::EventList(e) => e.clone(),
            ClWaitListPtrEnum::EventSlice(e) => EventList::from(e),
            ClWaitListPtrEnum::EventPtrSlice(e) => EventList::from(e),
            ClWaitListPtrEnum::RefEventList(e) => (*e).clone(),
            ClWaitListPtrEnum::RefTraitObj(e) => e.into(),
            ClWaitListPtrEnum::BoxTraitObj(e) => e.into(),
        }
    }
}

impl Deref for EventList {
    type Target = [Event];

    #[inline]
    fn deref(&self) -> &[Event] {
        self.as_slice()
    }
}

impl DerefMut for EventList {
    #[inline]
    fn deref_mut(&mut self) -> &mut [Event] {
        self.as_mut_slice()
    }
}

impl IntoIterator for EventList {
    type Item = Event;
    type IntoIter = ::std::vec::IntoIter<Event>;

    // * TODO: Currently converts a contained array to a vec. Will need
    //   something better eventually (perhaps wait for impl Trait to
    //   stabilize).
    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        match self.inner {
            Inner::Array(a) => {
                let mut el = EventList { inner: Inner::Array(a) };
                el.convert();
                el.into_iter()
            },
            Inner::Vec(v) => v.into_iter(),
        }
    }
}

impl Future for EventList {
    type Item = ();
    type Error = OclError;

    /// Removes (pops) each event from this list and waits for it to complete,
    /// dropping it in the process.
    //
    // * NOTE: Multiple calls to poll may hit this function. Do not attempt to
    //   remove any events from this list which still require waiting. The
    //   most robust strategy so far seems to simply wait on each event
    //   individually. Since events do not need to be polled or otherwise
    //   driven to completion this seems as efficient a strategy as any other.
    //
    //   Using `future::join_all` requires that the event list be cloned on
    //   each call to poll and then requires that each event be unnecessarily
    //   queried for completion an additional time. The only way around this
    //   would be to keep a separate variable for completion status but this
    //   variable would become out of date if the list were changed.
    //
    //   The most efficient strategy of all would probably be to use a marker
    //   instead of an event wait list and just never poll an `EventList` in
    //   the first place.
    //
    // * ALSO NOTE: The event being waited on is actually dropped (at the exit
    //   of the `while let` loop) and is kept alive by the runtime until its
    //   command is complete.
    //
    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        if PRINT_DEBUG { println!("##### EventList::poll: Polling Event list (thread: '{}').",
            ::std::thread::current().name().unwrap_or("<unnamed>")); }

        while let Some(event) = self.pop() {
            if cfg!(feature = "async_block") {
                event.wait_for()?;
            } else {
                if !event.is_complete()? {
                    #[cfg(not(feature = "async_block"))]
                    event.set_unpark_callback()?;
                    if PRINT_DEBUG { println!("######  ... callback set for event: {:?}.", event); }
                    return Ok(Async::NotReady);
                }
            }
        }

        // let res = future::join_all(self.events.clone()).poll().map(|res| res.map(|_| ()) );
        if PRINT_DEBUG { println!("##### EventList::poll: All events complete (thread: '{}').",
            ::std::thread::current().name().unwrap_or("<unnamed>")); }

        Ok(Async::Ready(()))
        // res
    }
}

unsafe impl<'a> ClNullEventPtr for &'a mut EventList {
    #[inline] fn alloc_new(&mut self) -> *mut cl_event { self._alloc_new() }

    #[inline] unsafe fn clone_from<E: AsRef<EventCore>>(&mut self, ev: E) {
        assert!(ev.as_ref().is_valid());
        *self._alloc_new() = ev.as_ref().clone().into_raw()
    }
}

unsafe impl ClWaitListPtr for EventList {
    #[inline] unsafe fn as_ptr_ptr(&self) -> *const cl_event { self._as_ptr_ptr() }
    #[inline] fn count(&self) -> u32 { self._count() }
}

unsafe impl<'a> ClWaitListPtr for &'a EventList {
    #[inline] unsafe fn as_ptr_ptr(&self) -> *const cl_event { self._as_ptr_ptr() }
    #[inline] fn count(&self) -> u32 { self._count() }
}



/// A stack allocated array of `cl_event` pointers with a maximum length of 8.
///
/// Do not store this list beyond the enqueue call(s) with which this list is
/// first used. Use `EventList` or `EventArray` for a persistent list.
///
//
// * [NOTE]: Consider implementing using
//   `https://github.com/servo/rust-smallvec` instead.
//
#[derive(Debug, Clone)]
pub struct RawEventArray {
    list: [cl_event; 8],
    len: usize,
}

impl RawEventArray {
    pub unsafe fn null() -> RawEventArray {
        RawEventArray {
            list: [0 as cl_event; 8],
            len: 0,
        }
    }

    #[inline]
    pub fn push<E>(&mut self, e: E) where E: AsRef<EventCore> {
        if (self.len) < self.list.len() {
            self.list[(self.len)] = unsafe { *(e.as_ref().as_ptr_ref()) };
            self.len += 1;
        } else {
            panic!("RawEventArray::push: List is full.");
        }
    }

    #[inline]
    unsafe fn _as_ptr_ptr(&self) -> *const cl_event {
        if self.len > 0 {
            &self.list as *const _ as *const cl_event
        } else {
            0 as *const cl_event
        }
    }

    /// Enqueue a marker event representing the completion of each and every
    /// event in this list.
    pub fn to_marker(&self, queue: &Queue) -> OclResult<Option<Event>> {
        if self.list.is_empty() { return Ok(None); }
        queue.enqueue_marker(Some(self)).map(|marker_event| Some(marker_event))
    }

    /// Enqueue a marker event representing the completion of each and every
    /// event in this list.
    pub fn into_marker(self, queue: &Queue) -> OclResult<Option<Event>> {
        self.to_marker(queue)
    }

    /// Returns a slice of events in the list.
    pub fn as_slice(&self) -> &[cl_event] {
        &self.list[..self.len]
    }

    /// Returns a mutable slice of events in the list.
    #[inline]
    pub fn as_mut_slice(&mut self) -> &mut [cl_event] {
        &mut self.list[..self.len]
    }

    /// The number of events in this list.
    #[inline]
    pub fn len(&self) -> usize {
        self.len
    }
}

impl<'e, E> From<&'e [E]> for RawEventArray where E: Borrow<Event> {
    fn from(events: &[E]) -> RawEventArray {
        let mut list = unsafe { RawEventArray::null() };
        for e in events {
            list.push(e.borrow());
        }
        list
    }
}

impl<'e, E> From<&'e [Option<E>]> for RawEventArray where E: Borrow<Event> {
    fn from(events: &[Option<E>]) -> RawEventArray {
        let mut list = unsafe { RawEventArray::null() };
        for event in events {
            if let Some(ref e) = *event {
                list.push(e.borrow());
            }
        }
        list
    }
}

impl<'e, 'f, E> From<&'e [&'f Option<E>]> for RawEventArray where 'e: 'f, E: Borrow<Event> {
    fn from(events: &[&Option<E>]) -> RawEventArray {
        let mut list = unsafe { RawEventArray::null() };
        for &event in events {
            if let Some(ref e) = *event {
                list.push(e.borrow());
            }
        }
        list
    }
}

macro_rules! impl_raw_list_from_arrays {
    ($( $len:expr ),*) => ($(
        impl<'e, E> From<[E; $len]> for RawEventArray where E: Borrow<Event> {
            fn from(events: [E; $len]) -> RawEventArray {
                let mut list = unsafe { RawEventArray::null() };
                for e in &events {
                    list.push(e.borrow());
                }
                list
            }
        }

        impl<'e, E> From<[Option<E>; $len]> for RawEventArray where E: Borrow<Event> {
            fn from(events: [Option<E>; $len]) -> RawEventArray {
                let mut list = unsafe { RawEventArray::null() };
                for event in &events {
                    if let Some(ref e) = *event {
                        list.push(e.borrow());
                    }
                }
                list
            }
        }

        impl<'e, 'f, E> From<[&'f Option<E>; $len]> for RawEventArray where 'e: 'f, E: Borrow<Event> {
            fn from(events: [&'f Option<E>; $len]) -> RawEventArray {
                let mut list = unsafe { RawEventArray::null() };
                for &event in &events {
                    if let Some(ref e) = *event {
                        list.push(e.borrow());
                    }
                }
                list
            }
        }
    )*);
}

impl_raw_list_from_arrays!(1, 2, 3, 4, 5, 6, 7, 8);

unsafe impl ClWaitListPtr for RawEventArray {
    #[inline] unsafe fn as_ptr_ptr(&self) -> *const cl_event { self._as_ptr_ptr() }
    #[inline] fn count(&self) -> u32 { self.len as u32 }
}

unsafe impl<'a> ClWaitListPtr for &'a RawEventArray {
    #[inline] unsafe fn as_ptr_ptr(&self) -> *const cl_event { self._as_ptr_ptr() }
    #[inline] fn count(&self) -> u32 { self.len as u32 }
}



/// Conversion to a 'marker' event.
pub trait IntoMarker {
    fn into_marker(self, queue: &Queue) -> OclResult<Option<Event>>;
}

// impl<'e> IntoMarker for &'e [Event] {
//     fn into_marker(self, queue: &Queue) -> OclResult<Option<Event>> {
//         RawEventArray::from(self).into_marker (queue)
//     }
// }

impl<'s, 'e> IntoMarker for &'s [&'e Event] where 'e: 's {
    fn into_marker(self, queue: &Queue) -> OclResult<Option<Event>> {
        RawEventArray::from(self).into_marker(queue)
    }
}

impl<'s, 'e> IntoMarker for &'s [Option<&'e Event>] where 'e: 's {
    fn into_marker(self, queue: &Queue) -> OclResult<Option<Event>> {
        RawEventArray::from(self).into_marker(queue)
    }
}

impl<'s, 'o, 'e> IntoMarker for &'s [&'o Option<&'e Event>] where 'e: 's + 'o, 'o: 's {
    fn into_marker(self, queue: &Queue) -> OclResult<Option<Event>> {
        RawEventArray::from(self).into_marker(queue)
    }
}

macro_rules! impl_marker_arrays {
    ($( $len:expr ),*) => ($(
        // impl<'e> IntoMarker for [Event; $len] {
        //     fn into_marker(self, queue: &Queue) -> OclResult<Option<Event>> {
        //         RawEventArray::from(self).into_marker (queue)
        //     }
        // }

        impl<'s, 'e> IntoMarker for [&'e Event; $len] where 'e: 's {
            fn into_marker(self, queue: &Queue) -> OclResult<Option<Event>> {
                RawEventArray::from(self).into_marker(queue)
            }
        }

        impl<'s, 'e> IntoMarker for [Option<&'e Event>; $len] where 'e: 's {
            fn into_marker(self, queue: &Queue) -> OclResult<Option<Event>> {
                RawEventArray::from(self).into_marker(queue)
            }
        }

        impl<'s, 'o, 'e> IntoMarker for [&'o Option<&'e Event>; $len] where 'e: 's + 'o, 'o: 's {
            fn into_marker(self, queue: &Queue) -> OclResult<Option<Event>> {
                RawEventArray::from(self).into_marker(queue)
            }
        }
    )*);
}

impl_marker_arrays!(1, 2, 3, 4, 5, 6, 7, 8);



/// Conversion to a stack allocated array of `cl_event` pointers.
pub trait IntoRawEventArray {
    fn into_raw_array(self) -> RawEventArray;
}

// impl<'e> IntoRawEventArray  for &'e [Event] {
//     fn into_raw_array(self) -> RawEventArray {
//         RawEventArray::from(self)
//     }
// }

impl<'s, 'e> IntoRawEventArray  for &'s [&'e Event] where 'e: 's {
    fn into_raw_array(self) -> RawEventArray {
        RawEventArray::from(self)
    }
}

impl<'s, 'e> IntoRawEventArray  for &'s [Option<&'e Event>] where 'e: 's {
    fn into_raw_array(self) -> RawEventArray {
        RawEventArray::from(self)
    }
}

impl<'s, 'o, 'e> IntoRawEventArray  for &'s [&'o Option<&'e Event>] where 'e: 's + 'o, 'o: 's {
    fn into_raw_array(self) -> RawEventArray {
        RawEventArray::from(self)
    }
}

macro_rules! impl_raw_list_arrays {
    ($( $len:expr ),*) => ($(
        // impl<'e> IntoRawEventArray  for [Event; $len] {
        //     fn into_raw_array(self) -> RawEventArray {
        //         RawEventArray::from(self)
        //     }
        // }

        impl<'s, 'e> IntoRawEventArray  for [&'e Event; $len] where 'e: 's {
            fn into_raw_array(self) -> RawEventArray {
                RawEventArray::from(self)
            }
        }

        impl<'s, 'e> IntoRawEventArray  for [Option<&'e Event>; $len] where 'e: 's {
            fn into_raw_array(self) -> RawEventArray {
                RawEventArray::from(self)
            }
        }

        impl<'s, 'o, 'e> IntoRawEventArray  for [&'o Option<&'e Event>; $len] where 'e: 's + 'o, 'o: 's {
            fn into_raw_array(self) -> RawEventArray {
                RawEventArray::from(self)
            }
        }
    )*);
}

impl_raw_list_arrays!(1, 2, 3, 4, 5, 6, 7, 8);