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
use std::borrow::Borrow;
use std::cell::UnsafeCell;
use std::marker;
use std::mem;
use std::ops::{Deref, Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive};
use std::slice;
use std::sync::Arc;

use wasm_bindgen::JsCast;
use web_sys::{WebGl2RenderingContext as GL, WebGlBuffer};

use crate::runtime::state::ContextUpdate;
use crate::runtime::{Connection, RenderingContext};
use crate::task::{ContextId, GpuTask, Progress};
use crate::util::JsId;

/// A GPU-accessible memory buffer that contains typed memory.
///
/// # Example
///
/// ```rust
/// # use web_glitz::runtime::RenderingContext;
/// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext + Clone + 'static {
/// use web_glitz::buffer::{Buffer, UsageHint};
///
/// let buffer: Buffer<[f32]> = context.create_buffer([1.0, 2.0, 3.0, 4.0], UsageHint::StreamDraw);
/// # }
/// ```
///
/// A buffer can be created with any data that implements [IntoBuffer].
pub struct Buffer<T>
where
    T: ?Sized,
{
    data: Arc<BufferData>,
    _marker: marker::PhantomData<Box<T>>,
}

impl<T> Buffer<T>
where
    T: ?Sized,
{
    pub(crate) fn data(&self) -> &Arc<BufferData> {
        &self.data
    }

    /// Returns the [UsageHint] that was specified for this [Buffer] when it was created.
    ///
    /// See [UsageHint] for details.
    pub fn usage_hint(&self) -> UsageHint {
        self.data.usage_hint
    }
}

impl<T> Buffer<T>
where
    T: Copy,
{
    /// Returns a command which, when executed will replace the data contained in this [Buffer] with
    /// the given `data`.
    pub fn upload_command<D>(&self, data: D) -> UploadCommand<T, D>
    where
        D: Borrow<T> + Send + Sync + 'static,
    {
        UploadCommand {
            buffer_data: self.data.clone(),
            data,
            offset_in_bytes: 0,
            len: 1,
            _marker: marker::PhantomData,
        }
    }

    /// Returns a command which, when executed will copy the data contained in this [Buffer] into a
    /// [Box].
    ///
    /// When the task is finished, the [Box] containing the copied data will be output.
    pub fn download_command(&self) -> DownloadCommand<T> {
        DownloadCommand {
            data: self.data.clone(),
            state: DownloadState::Initial,
            offset_in_bytes: 0,
            len: 1,
            _marker: marker::PhantomData,
        }
    }
}

impl<T> Buffer<[T]> {
    /// Returns the number of elements contained in this [Buffer].
    pub fn len(&self) -> usize {
        self.data.len
    }

    /// Returns a [BufferView] on an element or a slice of the elements this [Buffer], depending
    /// on the type of `index`.
    ///
    /// - If given a position, returns a view on the element at that position or `None` if out of
    ///   bounds.
    /// - If given a range, returns a view on the slice of elements corresponding to that range, or
    ///   `None` if out of bounds.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use web_glitz::runtime::RenderingContext;
    /// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext + Clone + 'static {
    /// use web_glitz::buffer::UsageHint;
    ///
    /// let buffer = context.create_buffer([1.0, 2.0, 3.0, 4.0], UsageHint::StreamDraw);
    ///
    /// buffer.get(1); // Some BufferView<f32> containing `2.0`
    /// buffer.get(1..3); // Some BufferView<[f32]> containing `[2.0, 3.0]`
    /// buffer.get(..2); // Some BufferView<[f32]> containing `[1.0 2.0]`
    /// buffer.get(4); // None (index out of bounds)
    /// # }
    /// ```
    pub fn get<I>(&self, index: I) -> Option<BufferView<I::Output>>
    where
        I: BufferSliceIndex<T>,
    {
        index.get(self)
    }

    /// Returns a [BufferView] on an element or a slice of the elements this [Buffer], depending
    /// on the type of `index`, without doing bounds checking.
    ///
    /// - If given a position, returns a view on the element at that position, without doing bounds
    ///   checking.
    /// - If given a range, returns a view on the slice of elements corresponding to that range,
    ///   without doing bounds checking.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use web_glitz::runtime::RenderingContext;
    /// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext + Clone + 'static {
    /// use web_glitz::buffer::UsageHint;
    ///
    /// let buffer = context.create_buffer([1.0, 2.0, 3.0, 4.0], UsageHint::StreamDraw);
    ///
    /// unsafe { buffer.get_unchecked(1) }; // BufferView<f32> containing `2.0`
    /// # }
    /// ```
    ///
    /// # Unsafe
    ///
    /// Only safe if `index` is in bounds. See [get] for a safe alternative.
    pub unsafe fn get_unchecked<I>(&self, index: I) -> BufferView<I::Output>
    where
        I: BufferSliceIndex<T>,
    {
        index.get_unchecked(self)
    }
}

impl<T> Buffer<[T]>
where
    T: Copy,
{
    /// Returns a command which, when executed will replace the elements contained in this [Buffer]
    /// with the elements in given `data`.
    ///
    /// If the `data` contains fewer elements than this [Buffer], then only the first `N` elements
    /// will be replaced, where `N` is the number of elements in the given `data`.
    ///
    /// If the `data` contains more elements than this [Buffer], then only the first `M` elements
    /// in the `data` will be used to update this [Buffer], where `M` is the number of elements in
    /// the [Buffer].
    pub fn upload_command<D>(&self, data: D) -> UploadCommand<[T], D>
    where
        D: Borrow<[T]> + Send + Sync + 'static,
    {
        UploadCommand {
            buffer_data: self.data.clone(),
            data,
            offset_in_bytes: 0,
            len: self.data.len,
            _marker: marker::PhantomData,
        }
    }

    /// Returns a command which, when executed will copy the elements contained in this [Buffer]
    /// into a [Box] as a boxed slice.
    ///
    /// When the task is finished, the [Box] containing the copied data will be output.
    pub fn download_command(&self) -> DownloadCommand<[T]> {
        DownloadCommand {
            data: self.data.clone(),
            state: DownloadState::Initial,
            offset_in_bytes: 0,
            len: self.data.len,
            _marker: marker::PhantomData,
        }
    }
}

impl<'a, T> Into<BufferView<'a, T>> for &'a Buffer<T>
where
    T: ?Sized,
{
    fn into(self) -> BufferView<'a, T> {
        BufferView {
            buffer: self,
            offset_in_bytes: 0,
            len: self.data.len,
        }
    }
}

impl<'a, T> Into<BufferViewMut<'a, T>> for &'a mut Buffer<T>
where
    T: ?Sized,
{
    fn into(self) -> BufferViewMut<'a, T> {
        BufferViewMut {
            inner: BufferView {
                buffer: self,
                offset_in_bytes: 0,
                len: self.data.len,
            },
            _marker: marker::PhantomData,
        }
    }
}

// TODO: CoerceUnsized doesn't currently work with only a PhantomData field...
//impl<T, U> CoerceUnsized<Buffer<U>> for Buffer<T>
//    where
//        T: Unsize<U> + ?Sized,
//        U: ?Sized,
//{}

/// A view on a segment or the whole of a [Buffer].
pub struct BufferView<'a, T>
where
    T: ?Sized,
{
    buffer: &'a Buffer<T>,
    pub(crate) offset_in_bytes: usize,
    len: usize,
}

impl<'a, T> BufferView<'a, T>
where
    T: ?Sized,
{
    pub(crate) fn buffer_data(&self) -> &Arc<BufferData> {
        self.buffer.data()
    }

    pub(crate) fn offset_in_bytes(&self) -> usize {
        self.offset_in_bytes
    }

    /// Returns the [UsageHint] that was specified for the [Buffer] view by this [BufferView] when
    /// it was created.
    ///
    /// See [UsageHint] for details.
    pub fn usage_hint(&self) -> UsageHint {
        self.buffer.data.usage_hint
    }
}

impl<'a, T> BufferView<'a, T>
where
    T: Copy,
{
    /// Returns a command which, when executed will replace the data viewed by this [BufferView]
    /// with the given `data`.
    ///
    /// This will modify the viewed [Buffer], the buffer (and any other views on the same data) will
    /// be affected by this change.
    pub fn upload_command<D>(&self, data: D) -> UploadCommand<T, D>
    where
        D: Borrow<T> + Send + Sync + 'static,
    {
        UploadCommand {
            buffer_data: self.buffer.data.clone(),
            data,
            offset_in_bytes: self.offset_in_bytes,
            len: 1,
            _marker: marker::PhantomData,
        }
    }

    /// Returns a command which, when executed will copy the data viewed by in this [BufferView]
    /// into a [Box].
    ///
    /// When the task is finished, the [Box] containing the copied data will be output.
    pub fn download_command(&self) -> DownloadCommand<T> {
        DownloadCommand {
            data: self.buffer.data.clone(),
            state: DownloadState::Initial,
            offset_in_bytes: self.offset_in_bytes,
            len: 1,
            _marker: marker::PhantomData,
        }
    }
}

impl<'a, T> Clone for BufferView<'a, T> {
    fn clone(&self) -> Self {
        BufferView {
            buffer: self.buffer,
            offset_in_bytes: self.offset_in_bytes,
            len: self.len,
        }
    }
}

impl<'a, T> Copy for BufferView<'a, T> {}

impl<'a, T> BufferView<'a, [T]> {
    /// Returns the number of elements contained in this [Buffer].
    pub fn len(&self) -> usize {
        self.len
    }

    /// Returns a [BufferView] on an element or a sub-slice of the elements this [Buffer], depending
    /// on the type of `index`.
    ///
    /// - If given a position, returns a view on the element at that position or `None` if out of
    ///   bounds.
    /// - If given a range, returns a view on the sub-slice of elements corresponding to that range,
    ///   or `None` if out of bounds.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use web_glitz::runtime::RenderingContext;
    /// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext + Clone + 'static {
    /// use web_glitz::buffer::UsageHint;
    ///
    /// let buffer = context.create_buffer([1.0, 2.0, 3.0, 4.0], UsageHint::StreamDraw);
    /// let view = buffer.view();
    ///
    /// view.get(1); // Some BufferView<f32> containing `2.0`
    /// view.get(1..3); // Some BufferView<[f32]> containing `[2.0, 3.0]`
    /// view.get(..2); // Some BufferView<[f32]> containing `[1.0 2.0]`
    /// view.get(4); // None (index out of bounds)
    /// # }
    /// ```
    pub fn get<I>(&self, index: I) -> Option<BufferView<I::Output>>
    where
        I: BufferViewSliceIndex<T>,
    {
        index.get(self)
    }

    /// Returns a [BufferView] on an element or a sub-slice of the elements this [BufferView],
    /// depending on the type of `index`, without doing bounds checking.
    ///
    /// - If given a position, returns a view on the element at that position, without doing bounds
    ///   checking.
    /// - If given a range, returns a view on the slice of elements corresponding to that range,
    ///   without doing bounds checking.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use web_glitz::runtime::RenderingContext;
    /// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext + Clone + 'static {
    /// use web_glitz::buffer::UsageHint;
    ///
    /// let buffer = context.create_buffer([1.0, 2.0, 3.0, 4.0], UsageHint::StreamDraw);
    /// let view = buffer.view();
    ///
    /// unsafe { view.get_unchecked(1) }; // BufferView<f32> containing `2.0`
    /// # }
    /// ```
    ///
    /// # Unsafe
    ///
    /// Only safe if `index` is in bounds. See [get] for a safe alternative.
    pub unsafe fn get_unchecked<I>(&self, index: I) -> BufferView<I::Output>
    where
        I: BufferViewSliceIndex<T>,
    {
        index.get_unchecked(self)
    }
}

impl<'a, T> BufferView<'a, [T]>
where
    T: Copy,
{
    /// Returns a command which, when executed will replace the elements viewed by this [BufferView]
    /// with the elements in given `data`.
    ///
    /// If the `data` contains fewer elements than the slice viewed by this [BufferView], then only
    /// the first `N` elements will be replaced, where `N` is the number of elements in the given
    /// `data`.
    ///
    /// If the `data` contains more elements than the slice viewed by this [Buffer], then only the
    /// first `M` elements in the `data` will be used to update this [Buffer], where `M` is the
    /// number of elements in the slice viewed by the [BufferView].
    ///
    /// This will modify the viewed [Buffer], the buffer (and any other views on the same data) will
    /// be affected by this change.
    pub fn upload_command<D>(&self, data: D) -> UploadCommand<[T], D>
    where
        D: Borrow<[T]> + Send + Sync + 'static,
    {
        UploadCommand {
            buffer_data: self.buffer.data.clone(),
            data,
            offset_in_bytes: self.offset_in_bytes,
            len: self.len,
            _marker: marker::PhantomData,
        }
    }

    /// Returns a command which, when executed will copy the elements viewed by in this [BufferView]
    /// into a [Box].
    ///
    /// When the task is finished, the [Box] containing the copied elements will be output.
    pub fn download_command(&self) -> DownloadCommand<[T]> {
        DownloadCommand {
            data: self.buffer.data.clone(),
            state: DownloadState::Initial,
            offset_in_bytes: self.offset_in_bytes,
            len: self.len,
            _marker: marker::PhantomData,
        }
    }
}

impl<'a, T> Clone for BufferView<'a, [T]> {
    fn clone(&self) -> Self {
        BufferView {
            buffer: self.buffer,
            offset_in_bytes: self.offset_in_bytes,
            len: self.len,
        }
    }
}

impl<'a, T> Copy for BufferView<'a, [T]> {}

pub struct BufferViewMut<'a, T>
where
    T: ?Sized,
{
    inner: BufferView<'a, T>,
    _marker: marker::PhantomData<&'a mut Buffer<T>>,
}

impl<'a, T> BufferViewMut<'a, [T]> {
    /// Returns a [BufferViewMut] on an element or a sub-slice of the elements this [BufferViewMut],
    /// depending on the type of `index`.
    ///
    /// - If given a position, returns a view on the element at that position or `None` if out of
    ///   bounds.
    /// - If given a range, returns a view on the sub-slice of elements corresponding to that range,
    ///   or `None` if out of bounds.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use web_glitz::runtime::RenderingContext;
    /// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext + Clone + 'static {
    /// use web_glitz::buffer::UsageHint;
    ///
    /// let buffer = context.create_buffer([1.0, 2.0, 3.0, 4.0], UsageHint::StreamDraw);
    /// let view = buffer.view();
    ///
    /// view.get(1); // Some BufferView<f32> containing `2.0`
    /// view.get(1..3); // Some BufferView<[f32]> containing `[2.0, 3.0]`
    /// view.get(..2); // Some BufferView<[f32]> containing `[1.0 2.0]`
    /// view.get(4); // None (index out of bounds)
    /// # }
    /// ```
    pub fn get_mut<I>(&mut self, index: I) -> Option<BufferViewMut<I::Output>>
    where
        I: BufferViewMutSliceIndex<T>,
    {
        index.get_mut(self)
    }

    /// Returns a [BufferViewMut] on an element or a sub-slice of the elements this [BufferViewMut],
    /// depending on the type of `index`, without doing bounds checking.
    ///
    /// - If given a position, returns a view on the element at that position, without doing bounds
    ///   checking.
    /// - If given a range, returns a view on the slice of elements corresponding to that range,
    ///   without doing bounds checking.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use web_glitz::runtime::RenderingContext;
    /// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext + Clone + 'static {
    /// use web_glitz::buffer::UsageHint;
    ///
    /// let buffer = context.create_buffer([1.0, 2.0, 3.0, 4.0], UsageHint::StreamDraw);
    /// let view = buffer.view();
    ///
    /// unsafe { view.get_unchecked(1) }; // BufferView<f32> containing `2.0`
    /// # }
    /// ```
    ///
    /// # Unsafe
    ///
    /// Only safe if `index` is in bounds. See [get_mut] for a safe alternative.
    pub unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> BufferViewMut<I::Output>
    where
        I: BufferViewMutSliceIndex<T>,
    {
        index.get_unchecked_mut(self)
    }
}

impl<'a, T> Deref for BufferViewMut<'a, T>
where
    T: ?Sized,
{
    type Target = BufferView<'a, T>;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

// TODO: CoerceUnsized doesn't currently work with only a PhantomData field...
//impl<'a, T, U> CoerceUnsized<BufferView<'a, U>> for BufferView<'a, T>
//where
//    T: Unsize<U> + ?Sized,
//    U: ?Sized,
//{}

/// Trait implemented for types that represent or contain data that may be stored in a [Buffer].
///
/// Uploading data to a buffer involves doing a bitwise copy, as does downloading data from a
/// buffer. WebGlitz relies on the semantics associated with the `Copy` trait to ensure that this
/// is safe and does not result in memory leaks.
pub trait IntoBuffer<T>
where
    T: ?Sized,
{
    /// Stores the data in a buffer belonging to the given [context], using the given [usage_hint].
    ///
    /// This consumes the Rust value and produces a GPU-accessible [Buffer] containing a bitwise
    /// copy of data.
    ///
    /// The usage hint may be used by the GPU driver for performance optimizations, see [UsageHint]
    /// for details.
    fn into_buffer<Rc>(self, context: &Rc, usage_hint: UsageHint) -> Buffer<T>
    where
        Rc: RenderingContext + Clone + 'static;
}

impl<D, T> IntoBuffer<T> for D
where
    D: Borrow<T> + 'static,
    T: Copy + 'static,
{
    fn into_buffer<Rc>(self, context: &Rc, usage_hint: UsageHint) -> Buffer<T>
    where
        Rc: RenderingContext + Clone + 'static,
    {
        let data = Arc::new(BufferData {
            id: UnsafeCell::new(None),
            context_id: context.id(),
            dropper: Box::new(context.clone()),
            usage_hint,
            len: 1,
        });

        context.submit(AllocateCommand {
            data: data.clone(),
            initial: self,
            _marker: marker::PhantomData,
        });

        Buffer {
            data,
            _marker: marker::PhantomData,
        }
    }
}

impl<D, T> IntoBuffer<[T]> for D
where
    D: Borrow<[T]> + 'static,
    T: Copy + 'static,
{
    fn into_buffer<Rc>(self, context: &Rc, usage_hint: UsageHint) -> Buffer<[T]>
    where
        Rc: RenderingContext + Clone + 'static,
    {
        let len = self.borrow().len();
        let data = Arc::new(BufferData {
            id: UnsafeCell::new(None),
            context_id: context.id(),
            dropper: Box::new(context.clone()),
            usage_hint,
            len,
        });

        context.submit(AllocateCommand::<D, [T]> {
            data: data.clone(),
            initial: self,
            _marker: marker::PhantomData,
        });

        Buffer {
            data,
            _marker: marker::PhantomData,
        }
    }
}

/// Enumerates the available usage hint for [Buffer]s.
///
/// A usage hint may be used to indicate to the GPU driver how you intend to use the data in the
/// [Buffer]. The driver may use this information for performance optimizations.
///
/// Note that this is merely a performance hint: it does not affect what you can or cannot do with
/// the [Buffer].
#[derive(Clone, Copy, Debug)]
pub enum UsageHint {
    /// Hints that the data will be uploaded once and read by the GPU repeatedly.
    StaticDraw,

    /// Hints that the data will be uploaded repeatedly and read by the GPU repeatedly.
    DynamicDraw,

    /// Hints that the data will be uploaded once and read by the GPU at most a few times.
    StreamDraw,

    /// Hints that the data will be written by the GPU once and will be downloaded repeatedly.
    StaticRead,

    /// Hints that the data will be written by the GPU repeatedly and will be downloaded repeatedly.
    DynamicRead,

    /// Hints that the data will be written by the GPU once and will be downloaded at most a few
    /// times.
    StreamRead,

    /// Hints that the data will be written by the GPU once and read by the GPU repeatedly.
    StaticCopy,

    /// Hints that the data will be written by the GPU repeatedly and read by the GPU repeatedly.
    DynamicCopy,

    /// Hints that the data will be written once by the GPU and read by the GPU at most a few times.
    StreamCopy,
}

impl UsageHint {
    fn gl_id(&self) -> u32 {
        match self {
            UsageHint::StaticDraw => GL::STATIC_DRAW,
            UsageHint::DynamicDraw => GL::DYNAMIC_DRAW,
            UsageHint::StreamDraw => GL::STREAM_DRAW,
            UsageHint::StaticRead => GL::STATIC_READ,
            UsageHint::DynamicRead => GL::DYNAMIC_READ,
            UsageHint::StreamRead => GL::STREAM_READ,
            UsageHint::StaticCopy => GL::STATIC_COPY,
            UsageHint::DynamicCopy => GL::DYNAMIC_COPY,
            UsageHint::StreamCopy => GL::STREAM_COPY,
        }
    }
}

/// A helper trait type for indexing operations on a [Buffer] that contains a slice.
pub trait BufferSliceIndex<T>: Sized {
    /// The output type returned by the indexing operations.
    type Output: ?Sized;

    /// Returns a view on the output for this operation if in bounds, or `None` otherwise.
    fn get(self, buffer: &Buffer<[T]>) -> Option<BufferView<Self::Output>>;

    /// Returns a view on the output for this operation, without performing any bounds checking.
    unsafe fn get_unchecked(self, buffer: &Buffer<[T]>) -> BufferView<Self::Output>;

    /// Returns a mutable view on the output for this operation if in bounds, or `None` otherwise.
    fn get_mut(self, buffer: &mut Buffer<[T]>) -> Option<BufferViewMut<Self::Output>> {
        self.get(buffer).map(|view| BufferViewMut {
            inner: view,
            _marker: marker::PhantomData,
        })
    }

    /// Returns a mutable view the output for this operation, without performing any bounds
    /// checking.
    unsafe fn get_unchecked_mut(self, buffer: &mut Buffer<[T]>) -> BufferViewMut<Self::Output> {
        BufferViewMut {
            inner: self.get_unchecked(buffer),
            _marker: marker::PhantomData,
        }
    }
}

impl<T> BufferSliceIndex<T> for usize {
    type Output = T;

    fn get(self, buffer: &Buffer<[T]>) -> Option<BufferView<Self::Output>> {
        if self < buffer.data.len {
            Some(BufferView {
                buffer: unsafe { mem::transmute(buffer) },
                offset_in_bytes: self * mem::size_of::<T>(),
                len: 1,
            })
        } else {
            None
        }
    }

    unsafe fn get_unchecked(self, buffer: &Buffer<[T]>) -> BufferView<Self::Output> {
        BufferView {
            buffer: mem::transmute(buffer),
            offset_in_bytes: self * mem::size_of::<T>(),
            len: 1,
        }
    }
}

impl<T> BufferSliceIndex<T> for RangeFull {
    type Output = [T];

    fn get(self, buffer: &Buffer<[T]>) -> Option<BufferView<Self::Output>> {
        Some(BufferView {
            buffer,
            offset_in_bytes: 0,
            len: buffer.data.len,
        })
    }

    unsafe fn get_unchecked(self, buffer: &Buffer<[T]>) -> BufferView<Self::Output> {
        BufferView {
            buffer,
            offset_in_bytes: 0,
            len: buffer.data.len,
        }
    }
}

impl<T> BufferSliceIndex<T> for Range<usize> {
    type Output = [T];

    fn get(self, buffer: &Buffer<[T]>) -> Option<BufferView<Self::Output>> {
        let Range { start, end } = self;

        if start > end || end > buffer.data.len {
            None
        } else {
            Some(BufferView {
                buffer,
                offset_in_bytes: start * mem::size_of::<T>(),
                len: end - start,
            })
        }
    }

    unsafe fn get_unchecked(self, buffer: &Buffer<[T]>) -> BufferView<Self::Output> {
        BufferView {
            buffer,
            offset_in_bytes: self.start * mem::size_of::<T>(),
            len: self.end - self.start,
        }
    }
}

impl<T> BufferSliceIndex<T> for RangeInclusive<usize> {
    type Output = [T];

    fn get(self, buffer: &Buffer<[T]>) -> Option<BufferView<Self::Output>> {
        if *self.end() == usize::max_value() {
            None
        } else {
            buffer.get(*self.start()..self.end() + 1)
        }
    }

    unsafe fn get_unchecked(self, buffer: &Buffer<[T]>) -> BufferView<Self::Output> {
        buffer.get_unchecked(*self.start()..self.end() + 1)
    }
}

impl<T> BufferSliceIndex<T> for RangeFrom<usize> {
    type Output = [T];

    fn get(self, buffer: &Buffer<[T]>) -> Option<BufferView<Self::Output>> {
        buffer.get(self.start..buffer.data.len)
    }

    unsafe fn get_unchecked(self, buffer: &Buffer<[T]>) -> BufferView<Self::Output> {
        buffer.get_unchecked(self.start..buffer.data.len)
    }
}

impl<T> BufferSliceIndex<T> for RangeTo<usize> {
    type Output = [T];

    fn get(self, buffer: &Buffer<[T]>) -> Option<BufferView<Self::Output>> {
        buffer.get(0..self.end)
    }

    unsafe fn get_unchecked(self, buffer: &Buffer<[T]>) -> BufferView<Self::Output> {
        buffer.get_unchecked(0..self.end)
    }
}

impl<T> BufferSliceIndex<T> for RangeToInclusive<usize> {
    type Output = [T];

    fn get(self, buffer: &Buffer<[T]>) -> Option<BufferView<Self::Output>> {
        buffer.get(0..=self.end)
    }

    unsafe fn get_unchecked(self, buffer: &Buffer<[T]>) -> BufferView<Self::Output> {
        buffer.get_unchecked(0..=self.end)
    }
}

/// A helper trait type for indexing operations on a [BufferView] that contains a slice.
pub trait BufferViewSliceIndex<T>: Sized {
    /// The output type returned by the indexing operations.
    type Output: ?Sized;

    /// Returns a view on the output for this operation if in bounds, or `None` otherwise.
    fn get<'a>(self, view: &'a BufferView<[T]>) -> Option<BufferView<'a, Self::Output>>;

    /// Returns a view on the output for this operation, without performing any bounds checking.
    unsafe fn get_unchecked<'a>(self, view: &'a BufferView<[T]>) -> BufferView<'a, Self::Output>;
}

impl<T> BufferViewSliceIndex<T> for usize {
    type Output = T;

    fn get<'a>(self, view: &'a BufferView<[T]>) -> Option<BufferView<'a, Self::Output>> {
        if self < view.len {
            Some(BufferView {
                buffer: unsafe { mem::transmute(view.buffer) },
                offset_in_bytes: view.offset_in_bytes + self * mem::size_of::<T>(),
                len: 1,
            })
        } else {
            None
        }
    }

    unsafe fn get_unchecked<'a>(self, view: &'a BufferView<[T]>) -> BufferView<'a, Self::Output> {
        BufferView {
            buffer: mem::transmute(view.buffer),
            offset_in_bytes: view.offset_in_bytes + self * mem::size_of::<T>(),
            len: 1,
        }
    }
}

impl<T> BufferViewSliceIndex<T> for RangeFull {
    type Output = [T];

    fn get<'a>(self, view: &'a BufferView<[T]>) -> Option<BufferView<'a, Self::Output>> {
        Some(BufferView {
            buffer: view.buffer,
            offset_in_bytes: view.offset_in_bytes,
            len: view.len,
        })
    }

    unsafe fn get_unchecked<'a>(self, view: &'a BufferView<[T]>) -> BufferView<'a, Self::Output> {
        BufferView {
            buffer: view.buffer,
            offset_in_bytes: view.offset_in_bytes,
            len: view.len,
        }
    }
}

impl<T> BufferViewSliceIndex<T> for Range<usize> {
    type Output = [T];

    fn get<'a>(self, view: &'a BufferView<[T]>) -> Option<BufferView<'a, Self::Output>> {
        let Range { start, end } = self;

        if start > end || end > view.len {
            None
        } else {
            Some(BufferView {
                buffer: view.buffer,
                offset_in_bytes: view.offset_in_bytes + start * mem::size_of::<T>(),
                len: end - start,
            })
        }
    }

    unsafe fn get_unchecked<'a>(self, view: &'a BufferView<[T]>) -> BufferView<'a, Self::Output> {
        BufferView {
            buffer: view.buffer,
            offset_in_bytes: view.offset_in_bytes + self.start * mem::size_of::<T>(),
            len: self.end - self.start,
        }
    }
}

impl<T> BufferViewSliceIndex<T> for RangeInclusive<usize> {
    type Output = [T];

    fn get<'a>(self, view: &'a BufferView<[T]>) -> Option<BufferView<'a, Self::Output>> {
        if *self.end() == usize::max_value() {
            None
        } else {
            view.get(*self.start()..self.end() + 1)
        }
    }

    unsafe fn get_unchecked<'a>(self, view: &'a BufferView<[T]>) -> BufferView<'a, Self::Output> {
        view.get_unchecked(*self.start()..self.end() + 1)
    }
}

impl<T> BufferViewSliceIndex<T> for RangeFrom<usize> {
    type Output = [T];

    fn get<'a>(self, view: &'a BufferView<[T]>) -> Option<BufferView<'a, Self::Output>> {
        view.get(self.start..view.len)
    }

    unsafe fn get_unchecked<'a>(self, view: &'a BufferView<[T]>) -> BufferView<'a, Self::Output> {
        view.get_unchecked(self.start..view.len)
    }
}

impl<T> BufferViewSliceIndex<T> for RangeTo<usize> {
    type Output = [T];

    fn get<'a>(self, view: &'a BufferView<[T]>) -> Option<BufferView<'a, Self::Output>> {
        view.get(0..self.end)
    }

    unsafe fn get_unchecked<'a>(self, view: &'a BufferView<[T]>) -> BufferView<'a, Self::Output> {
        view.get_unchecked(0..self.end)
    }
}

impl<T> BufferViewSliceIndex<T> for RangeToInclusive<usize> {
    type Output = [T];

    fn get<'a>(self, view: &'a BufferView<[T]>) -> Option<BufferView<'a, Self::Output>> {
        view.get(0..=self.end)
    }

    unsafe fn get_unchecked<'a>(self, view: &'a BufferView<[T]>) -> BufferView<'a, Self::Output> {
        view.get_unchecked(0..=self.end)
    }
}

/// A helper trait type for indexing operations on a [BufferViewMut] that contains a slice.
pub trait BufferViewMutSliceIndex<T>: BufferViewSliceIndex<T> {
    /// Returns a mutable view on the output for this operation if in bounds, or `None` otherwise.
    fn get_mut<'a>(
        self,
        view: &'a mut BufferViewMut<[T]>,
    ) -> Option<BufferViewMut<'a, Self::Output>> {
        self.get(view).map(|view| BufferViewMut {
            inner: view,
            _marker: marker::PhantomData,
        })
    }

    /// Returns a mutable view the output for this operation, without performing any bounds
    /// checking.
    unsafe fn get_unchecked_mut<'a>(
        self,
        view: &'a mut BufferViewMut<[T]>,
    ) -> BufferViewMut<'a, Self::Output> {
        BufferViewMut {
            inner: self.get_unchecked(view),
            _marker: marker::PhantomData,
        }
    }
}

/// Command for uploading data to a [Buffer] or a sub-section of a buffer as viewed by a
/// [BufferView].
///
/// See [Buffer::upload_command] and [BufferView::upload_command] for details.
pub struct UploadCommand<T, D>
where
    T: ?Sized,
{
    buffer_data: Arc<BufferData>,
    data: D,
    offset_in_bytes: usize,
    len: usize,
    _marker: marker::PhantomData<T>,
}

unsafe impl<T, D> GpuTask<Connection> for UploadCommand<T, D>
where
    D: Borrow<T>,
{
    type Output = ();

    fn context_id(&self) -> ContextId {
        ContextId::Id(self.buffer_data.context_id)
    }

    fn progress(&mut self, connection: &mut Connection) -> Progress<Self::Output> {
        let (gl, state) = unsafe { connection.unpack_mut() };

        unsafe {
            self.buffer_data
                .id()
                .unwrap()
                .with_value_unchecked(|buffer_object| {
                    state
                        .set_bound_copy_write_buffer(Some(&buffer_object))
                        .apply(gl)
                        .unwrap();
                });
        }

        unsafe {
            let data = slice::from_raw_parts(
                self.data.borrow() as *const _ as *const u8,
                mem::size_of::<T>(),
            );

            gl.buffer_sub_data_with_i32_and_u8_array(
                GL::COPY_WRITE_BUFFER,
                self.offset_in_bytes as i32,
                data,
            );
        };

        Progress::Finished(())
    }
}

unsafe impl<T, D> GpuTask<Connection> for UploadCommand<[T], D>
where
    D: Borrow<[T]>,
{
    type Output = ();

    fn context_id(&self) -> ContextId {
        ContextId::Id(self.buffer_data.context_id)
    }

    fn progress(&mut self, connection: &mut Connection) -> Progress<Self::Output> {
        let (gl, state) = unsafe { connection.unpack_mut() };

        unsafe {
            self.buffer_data
                .id()
                .unwrap()
                .with_value_unchecked(|buffer_object| {
                    state
                        .set_bound_copy_write_buffer(Some(&buffer_object))
                        .apply(gl)
                        .unwrap();
                });
        }

        let data = self.data.borrow();
        let size = data.len() * mem::size_of::<T>();
        let max_size = self.len * mem::size_of::<T>();

        unsafe {
            let mut data = slice::from_raw_parts(self.data.borrow() as *const _ as *const u8, size);

            if max_size < size {
                data = &data[0..max_size];
            }

            gl.buffer_sub_data_with_i32_and_u8_array(
                GL::COPY_WRITE_BUFFER,
                self.offset_in_bytes as i32,
                data,
            );
        };

        Progress::Finished(())
    }
}

/// Command for downloading data from a [Buffer] or a sub-section of a buffer as viewed by a
/// [BufferView].
///
/// See [Buffer::download_command] and [BufferView::download_command] for details.
pub struct DownloadCommand<T>
where
    T: ?Sized,
{
    data: Arc<BufferData>,
    state: DownloadState,
    offset_in_bytes: usize,
    len: usize,
    _marker: marker::PhantomData<T>,
}

enum DownloadState {
    Initial,
    Copied(Option<WebGlBuffer>),
}

unsafe impl<T> GpuTask<Connection> for DownloadCommand<T> {
    type Output = Box<T>;

    fn context_id(&self) -> ContextId {
        ContextId::Id(self.data.context_id)
    }

    fn progress(&mut self, connection: &mut Connection) -> Progress<Self::Output> {
        match self.state {
            DownloadState::Initial => {
                let (gl, state) = unsafe { connection.unpack_mut() };
                let read_buffer = GL::create_buffer(&gl).unwrap();
                let size_in_bytes = mem::size_of::<T>();

                state
                    .set_bound_copy_write_buffer(Some(&read_buffer))
                    .apply(gl)
                    .unwrap();

                gl.buffer_data_with_i32(
                    GL::COPY_WRITE_BUFFER,
                    size_in_bytes as i32,
                    GL::STREAM_READ,
                );

                unsafe {
                    self.data
                        .id()
                        .unwrap()
                        .with_value_unchecked(|buffer_object| {
                            state
                                .set_bound_copy_read_buffer(Some(&buffer_object))
                                .apply(gl)
                                .unwrap();
                        });
                }

                gl.copy_buffer_sub_data_with_i32_and_i32_and_i32(
                    GL::COPY_READ_BUFFER,
                    GL::COPY_WRITE_BUFFER,
                    self.offset_in_bytes as i32,
                    0,
                    size_in_bytes as i32,
                );

                mem::replace(&mut self.state, DownloadState::Copied(Some(read_buffer)));

                Progress::ContinueFenced
            }
            DownloadState::Copied(ref mut read_buffer) => {
                let read_buffer = read_buffer
                    .take()
                    .expect("Cannot make progress on a BufferDownload task after it has finished");
                let (gl, state) = unsafe { connection.unpack_mut() };

                state
                    .set_bound_copy_read_buffer(Some(&read_buffer))
                    .apply(gl)
                    .unwrap();

                let size_in_bytes = self.len * mem::size_of::<T>();
                let mut data = vec![0; size_in_bytes];

                gl.get_buffer_sub_data_with_i32_and_u8_array(GL::COPY_READ_BUFFER, 0, &mut data);

                gl.delete_buffer(Some(&read_buffer));

                let value = unsafe { Box::from_raw(mem::transmute(data.as_mut_ptr())) };

                mem::forget(data);

                Progress::Finished(value)
            }
        }
    }
}

unsafe impl<T> GpuTask<Connection> for DownloadCommand<[T]> {
    type Output = Box<[T]>;

    fn context_id(&self) -> ContextId {
        ContextId::Id(self.data.context_id)
    }

    fn progress(&mut self, connection: &mut Connection) -> Progress<Self::Output> {
        match self.state {
            DownloadState::Initial => {
                let (gl, state) = unsafe { connection.unpack_mut() };
                let read_buffer = GL::create_buffer(&gl).unwrap();
                let size_in_bytes = self.len * mem::size_of::<T>();

                state
                    .set_bound_copy_write_buffer(Some(&read_buffer))
                    .apply(gl)
                    .unwrap();

                gl.buffer_data_with_i32(
                    GL::COPY_WRITE_BUFFER,
                    size_in_bytes as i32,
                    GL::STREAM_READ,
                );

                unsafe {
                    self.data
                        .id()
                        .unwrap()
                        .with_value_unchecked(|buffer_object| {
                            state
                                .set_bound_copy_read_buffer(Some(&buffer_object))
                                .apply(gl)
                                .unwrap();
                        });
                }

                gl.copy_buffer_sub_data_with_i32_and_i32_and_i32(
                    GL::COPY_READ_BUFFER,
                    GL::COPY_WRITE_BUFFER,
                    self.offset_in_bytes as i32,
                    0,
                    size_in_bytes as i32,
                );

                mem::replace(&mut self.state, DownloadState::Copied(Some(read_buffer)));

                Progress::ContinueFenced
            }
            DownloadState::Copied(ref mut read_buffer) => {
                let read_buffer = read_buffer
                    .take()
                    .expect("Cannot make progress on a BufferDownload task after it has finished");
                let (gl, state) = unsafe { connection.unpack_mut() };

                state
                    .set_bound_copy_read_buffer(Some(&read_buffer))
                    .apply(gl)
                    .unwrap();

                let size_in_bytes = self.len * mem::size_of::<T>();
                let mut data = vec![0; size_in_bytes];

                gl.get_buffer_sub_data_with_i32_and_u8_array(GL::COPY_READ_BUFFER, 0, &mut data);

                gl.delete_buffer(Some(&read_buffer));

                unsafe {
                    let ptr = mem::transmute(data.as_mut_ptr());
                    let slice = slice::from_raw_parts_mut(ptr, self.len);
                    let boxed = Box::from_raw(slice);

                    mem::forget(data);

                    Progress::Finished(boxed)
                }
            }
        }
    }
}

trait BufferObjectDropper {
    fn drop_buffer_object(&self, id: JsId);
}

impl<T> BufferObjectDropper for T
where
    T: RenderingContext,
{
    fn drop_buffer_object(&self, id: JsId) {
        self.submit(DropCommand { id });
    }
}

pub(crate) struct BufferData {
    id: UnsafeCell<Option<JsId>>,
    context_id: usize,
    dropper: Box<dyn BufferObjectDropper>,
    len: usize,
    usage_hint: UsageHint,
}

impl BufferData {
    pub(crate) fn id(&self) -> Option<JsId> {
        unsafe { *self.id.get() }
    }

    pub(crate) fn context_id(&self) -> usize {
        self.context_id
    }
}

impl Drop for BufferData {
    fn drop(&mut self) {
        if let Some(id) = self.id() {
            self.dropper.drop_buffer_object(id);
        }
    }
}

struct AllocateCommand<D, T>
where
    T: ?Sized,
{
    data: Arc<BufferData>,
    initial: D,
    _marker: marker::PhantomData<T>,
}

unsafe impl<D, T> GpuTask<Connection> for AllocateCommand<D, T>
where
    D: Borrow<T>,
{
    type Output = ();

    fn context_id(&self) -> ContextId {
        ContextId::Any
    }

    fn progress(&mut self, connection: &mut Connection) -> Progress<Self::Output> {
        let (gl, state) = unsafe { connection.unpack_mut() };
        let data = &self.data;

        let buffer_object = GL::create_buffer(&gl).unwrap();

        state
            .set_bound_copy_write_buffer(Some(&buffer_object))
            .apply(gl)
            .unwrap();

        unsafe {
            let initial = slice::from_raw_parts(
                self.initial.borrow() as *const _ as *const u8,
                mem::size_of::<T>(),
            );

            gl.buffer_data_with_u8_array(GL::COPY_WRITE_BUFFER, initial, data.usage_hint.gl_id());
        }

        unsafe {
            *data.id.get() = Some(JsId::from_value(buffer_object.into()));
        }

        Progress::Finished(())
    }
}

unsafe impl<D, T> GpuTask<Connection> for AllocateCommand<D, [T]>
where
    D: Borrow<[T]>,
{
    type Output = ();

    fn context_id(&self) -> ContextId {
        ContextId::Any
    }

    fn progress(&mut self, connection: &mut Connection) -> Progress<Self::Output> {
        let (gl, state) = unsafe { connection.unpack_mut() };
        let data = &self.data;

        let buffer_object = GL::create_buffer(&gl).unwrap();

        state
            .set_bound_copy_write_buffer(Some(&buffer_object))
            .apply(gl)
            .unwrap();

        unsafe {
            let initial = self.initial.borrow();
            let size = initial.len() * mem::size_of::<T>();
            let initial = slice::from_raw_parts(initial as *const _ as *const u8, size);

            gl.buffer_data_with_u8_array(GL::COPY_WRITE_BUFFER, initial, data.usage_hint.gl_id());
        }

        unsafe {
            *data.id.get() = Some(JsId::from_value(buffer_object.into()));
        }

        Progress::Finished(())
    }
}

struct DropCommand {
    id: JsId,
}

unsafe impl GpuTask<Connection> for DropCommand {
    type Output = ();

    fn context_id(&self) -> ContextId {
        ContextId::Any
    }

    fn progress(&mut self, connection: &mut Connection) -> Progress<Self::Output> {
        let (gl, state) = unsafe { connection.unpack_mut() };

        state
            .vertex_array_cache_mut()
            .remove_buffer_dependents(self.id, gl);

        let value = unsafe { JsId::into_value(self.id) };

        gl.delete_buffer(Some(&value.unchecked_into()));

        Progress::Finished(())
    }
}