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
//! An `OpenCL` kernel.

use std;
use std::ops::{Deref, DerefMut};
use std::any::Any;
// use std::rc::{Rc};
// use std::cell::{RefCell};
use std::sync::{Arc, Mutex};
use std::collections::HashMap;
use core::{self, OclPrm, Kernel as KernelCore, CommandQueue as CommandQueueCore, Mem as MemCore,
    KernelArg, KernelInfo, KernelInfoResult, KernelArgInfo, KernelArgInfoResult,
    KernelWorkGroupInfo, KernelWorkGroupInfoResult, AsMem, MemCmdAll, ClVersions};
use core::error::{Result as OclResult, Error as OclError};
use standard::{SpatialDims, Program, Queue, WorkDims, Sampler, Device, ClNullEventPtrEnum,
    ClWaitListPtrEnum};
pub use self::arg_type::{BaseType, Cardinality, ArgType};

const PRINT_DEBUG: bool = false;

/// A kernel command builder used to queue a kernel with a mix of default
/// and optionally specified arguments.
#[must_use = "commands do nothing unless enqueued"]
pub struct KernelCmd<'k> {
    queue: Option<&'k CommandQueueCore>,
    kernel: &'k KernelCore,
    gwo: SpatialDims,
    gws: SpatialDims,
    lws: SpatialDims,
    wait_list: Option<ClWaitListPtrEnum<'k>>,
    new_event: Option<ClNullEventPtrEnum<'k>>,
}

/// A kernel enqueue command.
///
/// [UNSTABLE]: Methods still being tuned.
impl<'k> KernelCmd<'k> {
    /// Specifies a queue to use for this call only.
    pub fn queue<'q, Q>(mut self, queue: &'q Q) -> KernelCmd<'k>
            where 'q: 'k, Q: 'k + AsRef<CommandQueueCore>
    {
        self.queue = Some(queue.as_ref());
        self
    }

    /// Specifies a global work offset for this call only.
     pub fn gwo<D: Into<SpatialDims>>(mut self, gwo: D) -> KernelCmd<'k> {
        self.gwo = gwo.into();
        self
    }

    /// Specifies a global work size for this call only.
    pub fn gws<D: Into<SpatialDims>>(mut self, gws: D) -> KernelCmd<'k> {
        self.gws = gws.into();
        self
    }

    /// Specifies a local work size for this call only.
    pub fn lws<D: Into<SpatialDims>>(mut self, lws: D) -> KernelCmd<'k> {
        self.lws = lws.into();
        self
    }


    /// Specifies a list of events to wait on before the command will run.
    pub fn ewait<'e, Ewl>(mut self, ewait: Ewl) -> KernelCmd<'k>
            where 'e: 'k, Ewl: Into<ClWaitListPtrEnum<'e>>
    {
        self.wait_list = Some(ewait.into());
        self
    }

    /// Specifies a list of events to wait on before the command will run or
    /// resets it to `None`.
    pub fn ewait_opt<'e, Ewl>(mut self, ewait: Option<Ewl>) -> KernelCmd<'k>
            where 'e: 'k, Ewl: Into<ClWaitListPtrEnum<'e>>
    {
        self.wait_list = ewait.map(|el| el.into());
        self
    }

    /// Specifies the destination list or empty event for a new, optionally
    /// created event associated with this command.
    // pub fn enew(mut self, new_event_dest: &'k mut ClNullEventPtr) -> KernelCmd<'k> {
    pub fn enew<'e, En>(mut self, new_event_dest: En) -> KernelCmd<'k>
            where 'e: 'k, En: Into<ClNullEventPtrEnum<'e>>
    {
        self.new_event = Some(new_event_dest.into());
        self
    }

    /// Specifies a destination list for a new, optionally created event
    /// associated with this command.
    pub fn enew_opt<'e, En>(mut self, new_event_list: Option<En>) -> KernelCmd<'k>
            where 'e: 'k, En: Into<ClNullEventPtrEnum<'e>>
    {
        self.new_event = new_event_list.map(|e| e.into());
        self
    }

    /// Enqueues this kernel command.
    pub fn enq(self) -> OclResult<()> {
        let queue = match self.queue {
            Some(q) => q,
            None => return Err("KernelCmd::enq: No queue specified.".into()),
        };

        let dim_count = self.gws.dim_count();

        let gws = match self.gws.to_work_size() {
            Some(gws) => gws,
            None => return OclError::err_string("ocl::KernelCmd::enqueue: Global Work Size ('gws') \
                cannot be left unspecified. Set a default for the kernel or pass a valid parameter."),
        };

        if PRINT_DEBUG {
            println!("Enqueuing kernel: '{}'...",
                core::get_kernel_info(self.kernel, KernelInfo::FunctionName));
        }

        core::enqueue_kernel(queue, self.kernel, dim_count, self.gwo.to_work_offset(),
            &gws, self.lws.to_work_size(), self.wait_list, self.new_event)
    }
}


/// A kernel which represents a 'procedure'.
///
/// Corresponds to code which must have already been compiled into a program.
///
/// Set arguments using any of the `::arg...` (builder-style) or
/// `::set_arg...` functions or use `::set_arg` to set arguments by index.
///
/// `Kernel` includes features that a raw OpenCL kernel does not, including:
///
/// 1. Type-checked arguments (not just size-checked)
/// 2. Named arguments (with a `&'static str` name)
/// 3. Prevention of a potential (difficult to debug) segfault if a buffer or
///    image used by a kernel is dropped prematurely.
/// 4. Stored defaults for the:
///     - Queue
///     - Global Work Offset
///     - Global Work Size
///     - Local Work Size
//
// ### `Clone`, `Send`, and segfaults
//
// Every struct field of `Kernel` is safe to `Send` and `Clone` (after all of
// the arguments are specified) with the exception of `mem_args`. In order to
// keep references to buffers/images alive throughout the life of the kernel
// and prevent nasty, platform-dependent, and very hard to debug segfaults,
// storing `MemCore`s (buffers/images) is necessary. However, storing them
// means that there are compromises in other areas. The following are the
// options as I see them:
//
// 1. Store buffers/images in an Rc<RefCell>. This allows us to
//    `Clone` but not to `Send` between threads.
// 2. [CURRENT] Store buffers/images in an Arc<Mutex/RwLock> allowing both `Clone` and
//    `Send` at the cost of performance (could add up if users constantly
//    change arguments) [UPDATE]: Performance cost of this is below negligible.
// 3. [PREVIOUS] Disallow cloning and sending.
// 4. Don't store buffer/image references and let them segfault if the user
//    doesn't keep them alive properly.
//
// Please provide feedback by filing an [issue] if you have thoughts,
// suggestions, or alternative ideas.
//
// [issue]: https://github.com/cogciprocate/ocl/issues
//
// * TODO: Add more details, examples, etc.
// * TODO: Add information about panics and errors.
// * TODO: Finish arg info formatting.
//
#[derive(Debug)]
pub struct Kernel {
    obj_core: KernelCore,
    named_args: Option<HashMap<&'static str, u32>>,
    // mem_args: Rc<RefCell<Vec<Option<MemCore>>>>,
    mem_args: Arc<Mutex<Vec<Option<MemCore>>>>,
    new_arg_count: u32,
    queue: Option<Queue>,
    gwo: SpatialDims,
    gws: SpatialDims,
    lws: SpatialDims,
    num_args: u32,
    arg_types: Vec<ArgType>,
}


impl Kernel {
    /// Returns a new kernel.
    pub fn new<S: Into<String>>(name: S, program: &Program) -> OclResult<Kernel> {
        let name = name.into();
        let obj_core = try!(core::create_kernel(program, &name));

        let num_args = match core::get_kernel_info(&obj_core, KernelInfo::NumArgs) {
            KernelInfoResult::NumArgs(num) => num,
            KernelInfoResult::Error(e) => return Err(*e),
            _=> unreachable!(),
        };

        let mut arg_types = Vec::with_capacity(num_args as usize);

        for arg_idx in 0..num_args {
            arg_types.push(ArgType::from_kern_and_idx(&obj_core, arg_idx)?);
        }

        let mem_args = vec![None; num_args as usize];

        Ok(Kernel {
            obj_core: obj_core,
            named_args: None,
            new_arg_count: 0,
            // mem_args: Rc::new(RefCell::new(mem_args)),
            mem_args: Arc::new(Mutex::new(mem_args)),
            queue: None,
            gwo: SpatialDims::Unspecified,
            gws: SpatialDims::Unspecified,
            lws: SpatialDims::Unspecified,
            num_args: num_args,
            arg_types: arg_types,
        })
    }

    /// Sets the default queue to be used by all subsequent enqueue commands
    /// unless otherwise changed (with `::set_default_queue`) or overridden
    /// (by `::cmd().queue(...)...`).
    ///
    /// The queue must be associated with a device associated with the
    /// kernel's program.
    pub fn queue(mut self, queue: Queue) -> Kernel {
        self.queue = Some(queue);
        self
    }

    /// Sets the default global work offset (builder-style).
    ///
    /// Used when enqueuing kernel commands. Superseded if specified while
    /// making a call to enqueue or building a queue command with `::cmd`.
    pub fn gwo<D: Into<SpatialDims>>(mut self, gwo: D) -> Kernel {
        self.gwo = gwo.into();
        self
    }

    /// Sets the default global work size (builder-style).
    ///
    /// Used when enqueuing kernel commands. Superseded if specified while
    /// making a call to enqueue or building a queue command with `::cmd`.
    pub fn gws<D: Into<SpatialDims>>(mut self, gws: D) -> Kernel {
        self.gws = gws.into();
        self
    }

    /// Sets the default local work size (builder-style).
    ///
    /// Used when enqueuing kernel commands. Superseded if specified while
    /// making a call to enqueue or building a queue command with `::cmd`.
    pub fn lws<D: Into<SpatialDims>>(mut self, lws: D) -> Kernel {
        self.lws = lws.into();
        self
    }

    /// Adds a new argument to the kernel specifying the buffer object represented
    /// by 'buffer' (builder-style). Argument is added to the bottom of the argument
    /// order.
    // pub fn arg_buf<T: OclPrm>(mut self, buffer: &Buffer<T>) -> Kernel {
    pub fn arg_buf<T, M>(mut self, buffer: M) -> Kernel
            where T: OclPrm + 'static, M: AsMem<T> + MemCmdAll
    {
        self.new_arg_buf::<T, _>(Some(buffer));
        self
    }

    /// Adds a new argument to the kernel specifying the image object represented
    /// by 'image' (builder-style). Argument is added to the bottom of the argument
    /// order.
    pub fn arg_img<T, M>(mut self, image: M) -> Kernel
        where T: OclPrm, M: AsMem<T> + MemCmdAll
    {
        self.new_arg_img::<T, _>(Some(image));
        self
    }

    /// Adds a new argument to the kernel specifying the sampler object represented
    /// by 'sampler' (builder-style). Argument is added to the bottom of the argument
    /// order.
    pub fn arg_smp(mut self, sampler: &Sampler) -> Kernel {
        self.new_arg_smp(Some(sampler));
        self
    }

    /// Adds a new argument specifying the value: `scalar` (builder-style). Argument
    /// is added to the bottom of the argument order.
    pub fn arg_scl<T: OclPrm>(mut self, scalar: T) -> Kernel
            where T: OclPrm + 'static
    {
        self.new_arg_scl(Some(scalar));
        self
    }

    /// Adds a new argument specifying the value: `vector` (builder-style). Argument
    /// is added to the bottom of the argument order.
    pub fn arg_vec<T: OclPrm>(mut self, vector: T) -> Kernel
            where T: OclPrm + 'static
    {
        self.new_arg_vec(Some(vector));
        self
    }

    /// Adds a new argument specifying the allocation of a local variable of size
    /// `length * sizeof(T)` bytes (builder_style).
    ///
    /// Local variables are used to share data between work items in the same
    /// workgroup.
    pub fn arg_loc<T: OclPrm>(mut self, length: usize) -> Kernel
            where T: OclPrm + 'static
    {
        self.new_arg_loc::<T>(length);
        self
    }

    /// Adds a new named argument (in order) specifying the value: `scalar`
    /// (builder-style).
    ///
    /// Named arguments can be easily modified later using `::set_arg_scl_named()`.
    pub fn arg_scl_named<T: OclPrm>(mut self, name: &'static str, scalar_opt: Option<T>) -> Kernel
            where T: OclPrm + 'static
    {
        let arg_idx = self.new_arg_scl(scalar_opt);
        self.insert_named_arg(name, arg_idx);
        self
    }

    /// Adds a new named argument (in order) specifying the value: `vector`
    /// (builder-style).
    ///
    /// Named arguments can be easily modified later using `::set_arg_vec_named()`.
    pub fn arg_vec_named<T: OclPrm>(mut self, name: &'static str, vector_opt: Option<T>) -> Kernel
            where T: OclPrm + 'static
    {
        let arg_idx = self.new_arg_vec(vector_opt);
        self.insert_named_arg(name, arg_idx);
        self
    }

    /// Adds a new named argument specifying the buffer object represented by
    /// 'buffer' (builder-style). Argument is added to the bottom of the argument order.
    ///
    /// Named arguments can be easily modified later using `::set_arg_buf_named()`.
    pub fn arg_buf_named<T, M>(mut self, name: &'static str, buffer_opt: Option<M>) -> Kernel
            where T: OclPrm + 'static, M: AsMem<T> + MemCmdAll
    {
        let arg_idx = self.new_arg_buf::<T, _>(buffer_opt);
        self.insert_named_arg(name, arg_idx);
        self
    }

    /// Adds a new named argument specifying the image object represented by
    /// 'image' (builder-style). Argument is added to the bottom of the argument order.
    ///
    /// Named arguments can be easily modified later using `::set_arg_img_named()`.
    pub fn arg_img_named<T, M>(mut self, name: &'static str, image_opt: Option<M>) -> Kernel
            where T: OclPrm, M: AsMem<T> + MemCmdAll
    {
        let arg_idx = self.new_arg_img::<T, _>(image_opt);
        self.insert_named_arg(name, arg_idx);
        self
    }

    /// Adds a new named argument specifying the sampler object represented by
    /// 'sampler' (builder-style). Argument is added to the bottom of the argument order.
    ///
    /// Named arguments can be easily modified later using `::set_arg_smp_named()`.
    pub fn arg_smp_named(mut self, name: &'static str, sampler_opt: Option<&Sampler>) -> Kernel {
        let arg_idx = self.new_arg_smp(sampler_opt);
        self.insert_named_arg(name, arg_idx);
        self
    }

    /// Modifies the kernel argument named: `name`.
    ///
    /// ## Panics [FIXME]
    // [FIXME]: CHECK THAT NAME EXISTS AND GIVE A BETTER ERROR MESSAGE
    pub fn set_arg_scl_named<'a, T>(&'a mut self, name: &'static str, scalar: T)
            -> OclResult<&'a mut Kernel>
            where T: OclPrm + 'static
    {
        let arg_idx = try!(self.resolve_named_arg_idx(name));
        self._set_arg::<T>(arg_idx, KernelArg::Scalar(scalar))
            .and(Ok(self))
    }

    /// Modifies the kernel argument named: `name`.
    ///
    /// ## Panics [FIXME]
    // [FIXME]: CHECK THAT NAME EXISTS AND GIVE A BETTER ERROR MESSAGE
    pub fn set_arg_vec_named<'a, T>(&'a mut self, name: &'static str, vector: T)
            -> OclResult<&'a mut Kernel>
            where T: OclPrm + 'static
    {
        let arg_idx = try!(self.resolve_named_arg_idx(name));
        self._set_arg::<T>(arg_idx, KernelArg::Vector(vector))
            .and(Ok(self))
    }

    /// Modifies the kernel argument named: `name`.
    ///
    /// ## Panics [FIXME]
    // * [FIXME] TODO: CHECK THAT NAME EXISTS AND GIVE A BETTER ERROR MESSAGE
    pub fn set_arg_buf_named<'a, T, M>(&'a mut self, name: &'static str,
            buffer_opt: Option<M>)
            -> OclResult<&'a mut Kernel>
            where T: OclPrm + 'static, M: AsMem<T> + MemCmdAll
    {
        //  * TODO: ADD A CHECK FOR A VALID NAME (KEY)
        let arg_idx = try!(self.resolve_named_arg_idx(name));
        match buffer_opt {
            Some(buffer) => {
                self._set_arg::<T>(arg_idx, KernelArg::Mem(buffer.as_mem()))
            },
            None => {
                self._set_arg::<T>(arg_idx, KernelArg::MemNull)
            },
        }.and(Ok(self))
    }

    /// Modifies the kernel argument named: `name`.
    ///
    /// ## Panics [FIXME]
    // * [FIXME] TODO: CHECK THAT NAME EXISTS AND GIVE A BETTER ERROR MESSAGE
    pub fn set_arg_img_named<'a, T, M>(&'a mut self, name: &'static str,
            image_opt: Option<M>)
            -> OclResult<&'a mut Kernel>
            where T: OclPrm + 'static, M: AsMem<T> + MemCmdAll
    {
        // * TODO: ADD A CHECK FOR A VALID NAME (KEY)
        let arg_idx = try!(self.resolve_named_arg_idx(name));
        match image_opt {
            Some(img) => {
                self._set_arg::<T>(arg_idx, KernelArg::Mem(img.as_mem()))
            },
            None => {
                self._set_arg::<T>(arg_idx, KernelArg::MemNull)
            },
        }.and(Ok(self))
    }

    /// Sets the value of a named sampler argument.
    ///
    /// ## Panics [FIXME]
    // [PLACEHOLDER] Set a named sampler argument
    #[allow(unused_variables)]
    pub fn set_arg_smp_named<'a, T: OclPrm>(&'a mut self, name: &'static str,
                sampler_opt: Option<&Sampler>) -> OclResult<&'a mut Kernel>
    {
        unimplemented!();
    }

    /// Returns a command builder which is used to chain parameters of an
    /// 'enqueue' command together.
    pub fn cmd(&self) -> KernelCmd {
        KernelCmd { queue: self.queue.as_ref().map(|q| q.as_ref()), kernel: &self.obj_core,
            gwo: self.gwo, gws: self.gws, lws: self.lws,
            wait_list: None, new_event: None }
    }

    /// Enqueues this kernel on the default queue and returns the result.
    ///
    /// Shorthand for `.cmd().enq()`
    ///
    /// # Safety
    ///
    /// All kernel code must be considered unsafe. Therefore the act of
    /// calling this function contains implied unsafety even though the API
    /// itself is safe. How best to express that without the ambiguity of
    /// being marked `unsafe` while maintaining zero extra runtime overhead is
    /// still under consideration. Please provide feedback by filing an issue
    /// if you have any thoughts on the matter.
    ///
    pub fn enq(&self) -> OclResult<()> {
        self.cmd().enq()
    }

    /// Changes the default queue.
    ///
    /// Returns a ref for chaining i.e.:
    ///
    /// `kernel.set_default_queue(queue).enqueue(....);`
    ///
    /// Even when used as above, the queue is changed permanently,
    /// not just for the one call. Changing the queue is cheap so feel free
    /// to change as often as needed.
    ///
    /// If you want to change the queue for only a single call, use:
    /// `::cmd.queue(...)...enq()...`
    ///
    /// The new queue must be associated with a device associated with the
    /// kernel's program.
    ///
    pub fn set_default_queue(&mut self, queue: Queue) -> &mut Kernel {
        self.queue = Some(queue);
        self
    }

    /// Returns the default queue for this kernel.
    pub fn default_queue(&self) -> Option<&Queue> {
        self.queue.as_ref()
    }

    /// Returns the default global work offset.
    pub fn get_gwo(&self) -> SpatialDims {
        self.gwo
    }

    /// Returns the default global work size.
    pub fn get_gws(&self) -> SpatialDims {
        self.gws
    }

    /// Returns the default local work size.
    pub fn get_lws(&self) -> SpatialDims {
        self.lws
    }

    /// Returns the number of arguments specified for this kernel.
    #[inline]
    pub fn new_arg_count(&self) -> u32 {
        self.new_arg_count
    }

    /// Returns a reference to the core pointer wrapper, usable by functions in
    /// the `core` module.
    #[deprecated(since="0.13.0", note="Use `::core` instead.")]
    pub fn core_as_ref(&self) -> &KernelCore {
        &self.obj_core
    }

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

    /// Returns information about this kernel.
    pub fn info(&self, info_kind: KernelInfo) -> KernelInfoResult {
        core::get_kernel_info(&self.obj_core, info_kind)
    }

    /// Returns argument information for this kernel.
    pub fn arg_info(&self, arg_index: u32, info_kind: KernelArgInfo) -> KernelArgInfoResult {
        arg_info(self, arg_index, info_kind)
    }

    /// Returns work group information for this kernel.
    pub fn wg_info(&self, device: Device, info_kind: KernelWorkGroupInfo)
            -> KernelWorkGroupInfoResult
    {
        core::get_kernel_work_group_info(&self.obj_core, device, info_kind)
    }

    /// Returns the name of this kernel.
    pub fn name(&self) -> String {
        core::get_kernel_info(&self.obj_core, KernelInfo::FunctionName).into()
    }

    /// Returns the number of arguments this kernel has.
    pub fn num_args(&self) -> u32 {
        match core::get_kernel_info(&self.obj_core, KernelInfo::NumArgs) {
            KernelInfoResult::NumArgs(num) => num,
            KernelInfoResult::Error(e) => panic!("{}", e),
            _=> unreachable!(),
        }
    }

    /// Returns the argument index of a named argument if it exists.
    pub fn named_arg_idx(&self, name: &'static str) -> Option<u32> {
        self.resolve_named_arg_idx(name).ok()
    }

    /// Verifies that a type matches the kernel arg info:
    pub fn verify_arg_type<T: OclPrm + Any>(&self, arg_index: u32) -> OclResult<()> {
        let arg_type = self.arg_types.get(arg_index as usize)
            .ok_or(format!("Kernel arg index out of range. (kernel: {}, index: {})",
                self.name(), arg_index))?;

        if arg_type.is_match::<T>() {
            Ok(())
        } else {
            let type_name = arg_type_name(&self.obj_core, arg_index)?;
            Err(format!("Kernel argument type mismatch. The argument at index [{}] \
                is a '{}' ({:?}).", arg_index, type_name, arg_type).into())
        }
    }

    /// Sets an argument by index without checks of any kind.
    ///
    /// Setting buffer or image (`cl_mem`) arguments this way may cause
    /// segfaults or errors if the buffer goes out of scope at any point
    /// before this kernel is dropped.
    ///
    /// This method also bypasses the check to determine if the type you are
    /// passing matches the type defined in your kernel.
    ///
    pub unsafe fn set_arg_unchecked<T: OclPrm>(&mut self, arg_idx: u32,
            arg: KernelArg<T>) -> OclResult<()>
    {
        core::set_kernel_arg::<T>(&self.obj_core, arg_idx, arg)
    }

    /// Sets an argument by index.
    fn _set_arg<T: OclPrm + 'static>(&mut self, arg_idx: u32, arg: KernelArg<T>) -> OclResult<()> {
        self.verify_arg_type::<T>(arg_idx)?;

        // If the `KernelArg` is a `Mem` variant, clone the `MemCore` it
        // refers to, store it in `self.mem_args`, and create a new
        // `KernelArg::Mem` referring to the locally stored copy. This prevents
        // a buffer which has gone out of scope from being erroneously referred
        // to when this kernel is enqueued and causing either a misleading
        // error message or a hard to debug segfault depending on the
        // platform.
        let arg = match arg {
            KernelArg::Mem(mem) => {
                // self.mem_args.borrow_mut()[arg_idx as usize] = Some(mem.clone());
                self.mem_args.lock().unwrap()[arg_idx as usize] = Some(mem.clone());
                KernelArg::Mem(&mem)
            },
            arg => arg,
        };

        core::set_kernel_arg::<T>(&self.obj_core, arg_idx, arg)
    }

    fn fmt_info(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        f.debug_struct("Kernel")
            .field("FunctionName", &self.info(KernelInfo::FunctionName))
            .field("ReferenceCount", &self.info(KernelInfo::ReferenceCount))
            .field("Context", &self.info(KernelInfo::Context))
            .field("Program", &self.info(KernelInfo::Program))
            .field("Attributes", &self.info(KernelInfo::Attributes))
            .finish()
    }

    // fn fmt_arg_info(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
    //     f.debug_struct("Kernel")
    //         .field("FunctionName", &self.info(KernelInfo::FunctionName))
    //         .field("ReferenceCount", &self.info(KernelInfo::ReferenceCount))
    //         .field("Context", &self.info(KernelInfo::Context))
    //         .field("Program", &self.info(KernelInfo::Program))
    //         .field("Attributes", &self.info(KernelInfo::Attributes))
    //         .finish()
    // }

    fn fmt_wg_info<D>(&self, f: &mut std::fmt::Formatter, devices: Vec<D>) -> std::fmt::Result
            where D: Into<Device>
    {
        for device in devices {
            let device = device.into();

            f.debug_struct("WorkGroup")
                .field("WorkGroupSize", &self.wg_info(device, KernelWorkGroupInfo::WorkGroupSize))
                .field("CompileWorkGroupSize", &self.wg_info(device, KernelWorkGroupInfo::CompileWorkGroupSize))
                .field("LocalMemSize", &self.wg_info(device, KernelWorkGroupInfo::LocalMemSize))
                .field("PreferredWorkGroupSizeMultiple",
                    &self.wg_info(device, KernelWorkGroupInfo::PreferredWorkGroupSizeMultiple))
                .field("PrivateMemSize", &self.wg_info(device, KernelWorkGroupInfo::PrivateMemSize))
                // .field("GlobalWorkSize", &self.wg_info(device, KernelWorkGroupInfo::GlobalWorkSize))
                .finish()?;

        }

        Ok(())
    }

    /// Panics if this kernel has already had all arguments assigned.
    fn assert_unlocked(&self) {
        assert!(self.new_arg_count < self.num_args, "This kernel has already had \
            all arguments specified. Check the argument list.");
    }

    /// Inserts a named argument into the name->idx map.
    fn insert_named_arg(&mut self, name: &'static str, arg_idx: u32) {
        if self.named_args.is_none() {
            self.named_args = Some(HashMap::with_capacity(8));
        }

        self.named_args.as_mut().unwrap().insert(name, arg_idx);
    }

    /// Resolves the index of a named argument with a friendly error message.
    fn resolve_named_arg_idx(&self, name: &'static str) -> OclResult<u32> {
        match self.named_args {
            Some(ref map) => {
                match map.get(name) {
                    Some(&ai) => Ok(ai),
                    None => OclError::err_string(format!("Kernel::set_arg_scl_named(): Invalid argument \
                        name: '{}'.", name)),
                }
            },
            None => Err("Kernel::resolve_named_arg_idx: No named arguments declared.".into()),
        }
    }

    /// Non-builder-style version of `::arg_buf()`.
    fn new_arg_buf<T, M>(&mut self, buffer_opt: Option<M>) -> u32
            where T: OclPrm + 'static, M: AsMem<T> + MemCmdAll
    {
        match buffer_opt {
            Some(buffer) => {
                self.new_arg::<T>(KernelArg::Mem(buffer.as_mem()))
            },
            None => {
                self.new_arg::<T>(KernelArg::MemNull)
            },
        }
    }

    /// Non-builder-style version of `::arg_img()`.
    fn new_arg_img<T, M>(&mut self, image_opt: Option<M>) -> u32
        where T: OclPrm, M: AsMem<T> + MemCmdAll
    {
        match image_opt {
            Some(image) => {
                // Type is ignored:
                self.new_arg::<u64>(KernelArg::Mem(image.as_mem()))
            },
            None => {
                self.new_arg::<u64>(KernelArg::MemNull)
            },
        }
    }

    /// Non-builder-style version of `::arg_img()`.
    fn new_arg_smp(&mut self, sampler_opt: Option<&Sampler>) -> u32 {
        match sampler_opt {
            Some(sampler) => {
                // Type is ignored:
                self.new_arg::<u64>(KernelArg::Sampler(sampler))
            },
            None => {
                self.new_arg::<u64>(KernelArg::SamplerNull)
            },
        }
    }

    /// Non-builder-style version of `::arg_scl()`.
    fn new_arg_scl<T>(&mut self, scalar_opt: Option<T>) -> u32
            where T: OclPrm + 'static
    {
        let scalar = match scalar_opt {
            Some(s) => s,
            None => Default::default(),
        };

        self.new_arg::<T>(KernelArg::Scalar(scalar))
    }

    /// Non-builder-style version of `::arg_vec()`.
    fn new_arg_vec<T>(&mut self, vector_opt: Option<T>) -> u32
            where T: OclPrm + 'static
    {

        let vector = match vector_opt {
            Some(s) => s,
            None => Default::default(),
        };

        self.new_arg::<T>(KernelArg::Vector(vector))
    }

    /// Non-builder-style version of `::arg_loc()`.
    fn new_arg_loc<T>(&mut self, length: usize) -> u32
            where T: OclPrm + 'static
    {
        self.new_arg::<T>(KernelArg::Local(&length))
    }

    /// Adds a new argument to the kernel and returns the index.
    fn new_arg<T>(&mut self, arg: KernelArg<T>) -> u32
            where T: OclPrm + 'static
    {
        self.assert_unlocked();
        let arg_idx = self.new_arg_count;

        match self._set_arg(arg_idx, arg) {
            Ok(_) => (),
            Err(err) => {
                panic!("Kernel::new_arg(kernel name: '{}' arg index: '{}'): {}",
                    self.name(), arg_idx, err);
            }
        }

        self.new_arg_count += 1;
        assert!(self.new_arg_count <= self.num_args);
        arg_idx
    }
}

impl Clone for Kernel {
    fn clone(&self) -> Kernel {
        assert!(self.new_arg_count == self.num_args, "Cannot clone kernel until all arguments \
            are specified. Use named arguments with 'None' values to specify arguments you \
            plan to assign a value to later.");

        Kernel {
            obj_core: self.obj_core.clone(),
            named_args: self.named_args.clone(),
            new_arg_count: self.new_arg_count.clone(),
            mem_args: self.mem_args.clone(),
            queue: self.queue.clone(),
            gwo: self.gwo.clone(),
            gws: self.gws.clone(),
            lws: self.lws.clone(),
            num_args: self.num_args.clone(),
            arg_types: self.arg_types.clone(),
        }
    }
}

impl std::fmt::Display for Kernel {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        try!(self.fmt_info(f));
        try!(write!(f, " "));
        self.fmt_wg_info(f, self.obj_core.devices().unwrap())
    }
}

impl Deref for Kernel {
    type Target = KernelCore;

    fn deref(&self) -> &KernelCore {
        &self.obj_core
    }
}

impl DerefMut for Kernel {
    fn deref_mut(&mut self) -> &mut KernelCore {
        &mut self.obj_core
    }
}


/// Returns argument information for a kernel.
pub fn arg_info(core: &KernelCore, arg_index: u32, info_kind: KernelArgInfo)
        -> KernelArgInfoResult
{
    let device_versions = match core.device_versions() {
        Ok(vers) => vers,
        Err(e) => return e.into(),
    };

    core::get_kernel_arg_info(core, arg_index, info_kind,
        Some(&device_versions))
}

/// Returns the type name for a kernel argument at the specified index.
pub fn arg_type_name(core: &KernelCore, arg_index: u32) -> OclResult<String> {
    match arg_info(core, arg_index, KernelArgInfo::TypeName) {
        KernelArgInfoResult::TypeName(type_name) => Ok(type_name),
        KernelArgInfoResult::Error(e) => Err(*e),
        _ => unreachable!(),
    }
}


pub mod arg_type {
    #![allow(unused_imports)]
    use std::any::{Any, TypeId};
    use ::{OclPrm, Result as OclResult};
    use ffi::{cl_char, cl_uchar, cl_short, cl_ushort, cl_int, cl_uint, cl_long, cl_ulong,
        cl_half, cl_float, cl_double, cl_bool, cl_bitfield};

    use core::{Error as OclError, Status};
    use core::Kernel as KernelCore;
    use standard::Sampler;
    use super::{arg_info, arg_type_name};

    pub use core::{
        Char, Char2, Char3, Char4, Char8, Char16,
        Uchar, Uchar2, Uchar3, Uchar4, Uchar8, Uchar16,
        Short, Short2, Short3, Short4, Short8, Short16,
        Ushort, Ushort2, Ushort3, Ushort4, Ushort8, Ushort16,
        Int, Int2, Int3, Int4, Int8, Int16,
        Uint, Uint2, Uint3, Uint4, Uint8, Uint16,
        Long, Long2, Long3, Long4, Long8, Long16,
        Ulong, Ulong2, Ulong3, Ulong4, Ulong8, Ulong16,
        Float, Float2, Float3, Float4, Float8, Float16,
        Double, Double2, Double3, Double4, Double8, Double16};

    // /// Returns a new argument type specifier.
    // pub fn arg_type(core: &KernelCore, arg_index: u32) -> OclResult<ArgType> {
    //     let type_name = arg_type_name(core, arg_index)?;
    //     ArgType::from_str(type_name.as_str())
    // }

    /// The base type of an OpenCL primitive.
    #[derive(Clone, Debug, Copy, PartialEq, Eq)]
    pub enum BaseType {
        Char,
        Uchar,
        Short,
        Ushort,
        Int,
        Uint,
        Long,
        Ulong,
        Float,
        Double,
        Sampler,
        Image,
        Unknown,
    }

    /// The cartinality of an OpenCL primitive.
    ///
    /// (ex. `float4`: 4)
    #[derive(Clone, Debug, Copy, PartialEq, Eq)]
    pub enum Cardinality {
        One,
        Two,
        Three,
        Four,
        Eight,
        Sixteen,
    }

    /// The type of a kernel argument derived from its string representation.
    #[allow(dead_code)]
    #[derive(Clone, Debug)]
    pub struct ArgType {
        base_type: BaseType,
        cardinality: Cardinality,
        is_ptr: bool,
    }

    impl ArgType {
        /// Returns an `ArgType` that will always return `true` when calling
        /// `::is_match`.
        pub fn unknown() -> OclResult<ArgType> {
            Ok(ArgType {
                base_type: BaseType::Unknown,
                cardinality: Cardinality::One,
                is_ptr: false,
            })
        }

        /// Ascertains a `KernelArgType` from the contents of a
        /// `KernelArgInfoResult::TypeName`.
        ///
        /// * TODO: Optimize or outsource this if possible. Is `::contains`
        /// the fastest way to parse these in this situation? Should
        /// `::starts_with` be used for base type names instead?
        pub fn from_str(type_name: &str) -> OclResult<ArgType> {
            let is_ptr = type_name.contains("*");

            let card = if type_name.contains("16") {
                Cardinality::Sixteen
            } else if type_name.contains("8") {
                Cardinality::Eight
            } else if type_name.contains("4") {
                Cardinality::Four
            } else if type_name.contains("3") {
                Cardinality::Three
            } else if type_name.contains("2") {
                Cardinality::Two
            } else {
                Cardinality::One
            };

            let base = if type_name.contains("uchar") {
                BaseType::Uchar
            } else if type_name.contains("char") {
                BaseType::Char
            } else if type_name.contains("ushort") {
                BaseType::Ushort
            } else if type_name.contains("short") {
                BaseType::Short
            } else if type_name.contains("uint") {
                BaseType::Uint
            } else if type_name.contains("int") {
                BaseType::Int
            } else if type_name.contains("ulong") {
                BaseType::Ulong
            } else if type_name.contains("long") {
                BaseType::Long
            } else if type_name.contains("float") {
                BaseType::Float
            } else if type_name.contains("double") {
                BaseType::Double
            } else if type_name.contains("sampler") {
                BaseType::Sampler
            } else if type_name.contains("image") {
                BaseType::Image
            } else {
                // return Err(format!("Unable to determine type of: {}. Please file an issue at \
                //     'https://github.com/cogciprocate/ocl/issues'.", type_name).into());
                BaseType::Unknown
            };

            Ok(ArgType {
                base_type: base,
                cardinality: card,
                is_ptr: is_ptr,
            })
        }

        /// Returns a new argument type specifier.
        ///
        /// This function calls `core::get_kernel_arg_info`. Some platforms
        /// (Apple, NVIDIA) either do not implement
        /// `core::get_kernel_arg_info` or error in irregular ways. Known
        /// irregular errors are checked for here. The result of a call to
        /// `ArgType::unknown()` (which matches any argument type) is returned
        /// if any are found.
        pub fn from_kern_and_idx(core: &KernelCore, arg_index: u32) -> OclResult<ArgType> {
            use core::EmptyInfoResult;

            match arg_type_name(core, arg_index) {
                Ok(type_name) => ArgType::from_str(type_name.as_str()),
                Err(err) => {
                    // if let OclError::Status { ref status, .. } = err {
                    //     if status == &Status::CL_KERNEL_ARG_INFO_NOT_AVAILABLE {
                    //         return Ok(ArgType { base_type: BaseType::Unknown,
                    //             cardinality: Cardinality::One, is_ptr: false })
                    //     }
                    // } else

                    // if let OclError::EmptyInfoResult(EmptyInfoResult::KernelArg) = err {

                    // }

                    // Escape hatches for known, platform-specific errors.
                    match err {
                        OclError::Status { ref status, .. } => {
                            if status == &Status::CL_KERNEL_ARG_INFO_NOT_AVAILABLE {
                                return Ok(ArgType { base_type: BaseType::Unknown,
                                    cardinality: Cardinality::One, is_ptr: false })
                            }
                        },
                        OclError::EmptyInfoResult(EmptyInfoResult::KernelArg) => {
                            return ArgType::unknown();
                        },
                        _ => (),
                    }

                    Err(err)
                },
            }
        }

        /// Returns true if the type of `T` matches the base type of this `ArgType`.
        pub fn is_match<T: OclPrm + Any + 'static>(&self) -> bool {
            match self.base_type {
                BaseType::Char => {
                    let card_match = match self.cardinality {
                        Cardinality::One => TypeId::of::<cl_char>() == TypeId::of::<T>(),
                        Cardinality::Two => TypeId::of::<Char2>() == TypeId::of::<T>(),
                        Cardinality::Three => TypeId::of::<Char3>() == TypeId::of::<T>(),
                        Cardinality::Four => TypeId::of::<Char4>() == TypeId::of::<T>(),
                        Cardinality::Eight => TypeId::of::<Char8>() == TypeId::of::<T>(),
                        Cardinality::Sixteen => TypeId::of::<Char16>() == TypeId::of::<T>(),
                    };

                    if self.is_ptr {
                        TypeId::of::<cl_char>() == TypeId::of::<T>() || card_match
                    } else {
                        card_match
                    }
                },
                BaseType::Uchar => {
                    let card_match = match self.cardinality {
                        Cardinality::One => TypeId::of::<cl_uchar>() == TypeId::of::<T>(),
                        Cardinality::Two => TypeId::of::<Uchar2>() == TypeId::of::<T>(),
                        Cardinality::Three => TypeId::of::<Uchar3>() == TypeId::of::<T>(),
                        Cardinality::Four => TypeId::of::<Uchar4>() == TypeId::of::<T>(),
                        Cardinality::Eight => TypeId::of::<Uchar8>() == TypeId::of::<T>(),
                        Cardinality::Sixteen => TypeId::of::<Uchar16>() == TypeId::of::<T>(),
                    };

                    if self.is_ptr {
                        TypeId::of::<cl_uchar>() == TypeId::of::<T>() || card_match
                    } else {
                        card_match
                    }
                },
                BaseType::Short => {
                    let card_match = match self.cardinality {
                        Cardinality::One => TypeId::of::<cl_short>() == TypeId::of::<T>(),
                        Cardinality::Two => TypeId::of::<Short2>() == TypeId::of::<T>(),
                        Cardinality::Three => TypeId::of::<Short3>() == TypeId::of::<T>(),
                        Cardinality::Four => TypeId::of::<Short4>() == TypeId::of::<T>(),
                        Cardinality::Eight => TypeId::of::<Short8>() == TypeId::of::<T>(),
                        Cardinality::Sixteen => TypeId::of::<Short16>() == TypeId::of::<T>(),
                    };

                    if self.is_ptr {
                        TypeId::of::<cl_short>() == TypeId::of::<T>() || card_match
                    } else {
                        card_match
                    }
                },
                BaseType::Ushort => {
                    let card_match = match self.cardinality {
                        Cardinality::One => TypeId::of::<cl_ushort>() == TypeId::of::<T>(),
                        Cardinality::Two => TypeId::of::<Ushort2>() == TypeId::of::<T>(),
                        Cardinality::Three => TypeId::of::<Ushort3>() == TypeId::of::<T>(),
                        Cardinality::Four => TypeId::of::<Ushort4>() == TypeId::of::<T>(),
                        Cardinality::Eight => TypeId::of::<Ushort8>() == TypeId::of::<T>(),
                        Cardinality::Sixteen => TypeId::of::<Ushort16>() == TypeId::of::<T>(),
                    };

                    if self.is_ptr {
                        TypeId::of::<cl_ushort>() == TypeId::of::<T>() || card_match
                    } else {
                        card_match
                    }
                },
                BaseType::Int => {
                    let card_match = match self.cardinality {
                        Cardinality::One => TypeId::of::<cl_int>() == TypeId::of::<T>(),
                        Cardinality::Two => TypeId::of::<Int2>() == TypeId::of::<T>(),
                        Cardinality::Three => TypeId::of::<Int3>() == TypeId::of::<T>(),
                        Cardinality::Four => TypeId::of::<Int4>() == TypeId::of::<T>(),
                        Cardinality::Eight => TypeId::of::<Int8>() == TypeId::of::<T>(),
                        Cardinality::Sixteen => TypeId::of::<Int16>() == TypeId::of::<T>(),
                    };

                    if self.is_ptr {
                        TypeId::of::<cl_int>() == TypeId::of::<T>() || card_match
                    } else {
                        card_match
                    }
                },
                BaseType::Uint => {
                    let card_match = match self.cardinality {
                        Cardinality::One => TypeId::of::<cl_uint>() == TypeId::of::<T>(),
                        Cardinality::Two => TypeId::of::<Uint2>() == TypeId::of::<T>(),
                        Cardinality::Three => TypeId::of::<Uint3>() == TypeId::of::<T>(),
                        Cardinality::Four => TypeId::of::<Uint4>() == TypeId::of::<T>(),
                        Cardinality::Eight => TypeId::of::<Uint8>() == TypeId::of::<T>(),
                        Cardinality::Sixteen => TypeId::of::<Uint16>() == TypeId::of::<T>(),
                    };

                    if self.is_ptr {
                        TypeId::of::<cl_uint>() == TypeId::of::<T>() || card_match
                    } else {
                        card_match
                    }
                },
                BaseType::Long => {
                    let card_match = match self.cardinality {
                        Cardinality::One => TypeId::of::<cl_long>() == TypeId::of::<T>(),
                        Cardinality::Two => TypeId::of::<Long2>() == TypeId::of::<T>(),
                        Cardinality::Three => TypeId::of::<Long3>() == TypeId::of::<T>(),
                        Cardinality::Four => TypeId::of::<Long4>() == TypeId::of::<T>(),
                        Cardinality::Eight => TypeId::of::<Long8>() == TypeId::of::<T>(),
                        Cardinality::Sixteen => TypeId::of::<Long16>() == TypeId::of::<T>(),
                    };

                    if self.is_ptr {
                        TypeId::of::<cl_long>() == TypeId::of::<T>() || card_match
                    } else {
                        card_match
                    }
                },
                BaseType::Ulong => {
                    let card_match = match self.cardinality {
                        Cardinality::One => TypeId::of::<cl_ulong>() == TypeId::of::<T>(),
                        Cardinality::Two => TypeId::of::<Ulong2>() == TypeId::of::<T>(),
                        Cardinality::Three => TypeId::of::<Ulong3>() == TypeId::of::<T>(),
                        Cardinality::Four => TypeId::of::<Ulong4>() == TypeId::of::<T>(),
                        Cardinality::Eight => TypeId::of::<Ulong8>() == TypeId::of::<T>(),
                        Cardinality::Sixteen => TypeId::of::<Ulong16>() == TypeId::of::<T>(),
                    };

                    if self.is_ptr {
                        TypeId::of::<cl_ulong>() == TypeId::of::<T>() || card_match
                    } else {
                        card_match
                    }
                },
                BaseType::Float => {
                    let card_match = match self.cardinality {
                        Cardinality::One => TypeId::of::<cl_float>() == TypeId::of::<T>(),
                        Cardinality::Two => TypeId::of::<Float2>() == TypeId::of::<T>(),
                        Cardinality::Three => TypeId::of::<Float3>() == TypeId::of::<T>(),
                        Cardinality::Four => TypeId::of::<Float4>() == TypeId::of::<T>(),
                        Cardinality::Eight => TypeId::of::<Float8>() == TypeId::of::<T>(),
                        Cardinality::Sixteen => TypeId::of::<Float16>() == TypeId::of::<T>(),
                    };

                    if self.is_ptr {
                        TypeId::of::<cl_float>() == TypeId::of::<T>() || card_match
                    } else {
                        card_match
                    }
                },
                BaseType::Double => {
                    let card_match = match self.cardinality {
                        Cardinality::One => TypeId::of::<cl_double>() == TypeId::of::<T>(),
                        Cardinality::Two => TypeId::of::<Double2>() == TypeId::of::<T>(),
                        Cardinality::Three => TypeId::of::<Double3>() == TypeId::of::<T>(),
                        Cardinality::Four => TypeId::of::<Double4>() == TypeId::of::<T>(),
                        Cardinality::Eight => TypeId::of::<Double8>() == TypeId::of::<T>(),
                        Cardinality::Sixteen => TypeId::of::<Double16>() == TypeId::of::<T>(),
                    };

                    if self.is_ptr {
                        TypeId::of::<cl_double>() == TypeId::of::<T>() || card_match
                    } else {
                        card_match
                    }
                },
                BaseType::Sampler => TypeId::of::<u64>() == TypeId::of::<T>(),
                BaseType::Image => TypeId::of::<u64>() == TypeId::of::<T>(),
                // Everything matches if type was undetermined (escape hatch):
                BaseType::Unknown => true,
            }
        }

        #[allow(dead_code)]
        pub fn is_ptr(&self) -> bool {
            self.is_ptr
        }
    }

    impl<'a> From<&'a str> for ArgType {
        /// Ascertains a `KernelArgType` from the contents of a
        /// `KernelArgInfoResult::TypeName`.
        ///
        /// Panics if the string is not valid.
        fn from(type_name: &'a str) -> ArgType {
            ArgType::from_str(type_name).unwrap()
        }
    }
}