slop-alloc 6.1.0

Memory allocation backend abstraction for SLOP
Documentation
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
//! Fixed-capacity buffer with customizable memory backends.
//!
//! This module provides a `Buffer<T, A>` type, which is a contiguous array type
//! with heap-allocated contents. Unlike `Vec<T>`, buffers have a fixed capacity
//! determined at creation time and cannot grow beyond this capacity.
//!
//! # Key Differences from `Vec<T>`
//!
//! - **Fixed Capacity**: Buffers cannot reallocate to grow beyond their initial capacity
//! - **Backend Support**: Works with different memory allocators (CPU, GPU, etc.)
//! - **CPU Backend Exception**: Only `Buffer<T, CpuBackend>` supports capacity growth through
//!   conversion to/from `Vec<T>`
//!
//! # Examples
//!
//! ```rust,ignore
//! let mut buffer: Buffer<i32> = Buffer::with_capacity(10);
//! // The buffer can hold up to 10 elements
//! assert_eq!(buffer.len(), 0);
//! assert_eq!(buffer.capacity(), 10);
//!
//! // For non-CPU backends, this is the maximum capacity
//! // Attempting to exceed it will panic
//! ```

use serde::{Deserialize, Serialize, Serializer};
use slop_algebra::{ExtensionField, Field};

use crate::{
    backend::{Backend, CpuBackend, GLOBAL_CPU_BACKEND},
    mem::{CopyDirection, CopyError},
    slice::Slice,
    HasBackend, Init, RawBuffer, TryReserveError,
};
use std::{
    alloc::Layout,
    mem::{ManuallyDrop, MaybeUninit},
    ops::{
        Deref, DerefMut, Index, IndexMut, Range, RangeFrom, RangeFull, RangeInclusive, RangeTo,
        RangeToInclusive,
    },
};

/// A fixed-capacity buffer with heap-allocated contents.
///
/// This type provides a contiguous array with a fixed maximum capacity. For most backends,
/// the capacity is immutable after creation. Only `Buffer<T, CpuBackend>` can grow by
/// converting to/from `Vec<T>` internally.
///
/// # Type Parameters
///
/// - `T`: The type of elements stored in the buffer
/// - `A`: The backend allocator type (defaults to `CpuBackend`)
///
/// # Guarantees
///
/// - The memory it points to is allocated by the backend allocator `A`
/// - `length` <= `capacity`
/// - The first `length` values are properly initialized
/// - The capacity remains fixed for the lifetime of the buffer (except for `CpuBackend`)
#[derive(Debug)]
#[repr(C)]
pub struct Buffer<T, A: Backend = CpuBackend> {
    buf: RawBuffer<T, A>,
    len: usize,
}

unsafe impl<T, A: Backend> Send for Buffer<T, A> {}
unsafe impl<T, A: Backend> Sync for Buffer<T, A> {}

impl<T, A> Buffer<T, A>
where
    A: Backend,
{
    /// Constructs a new, empty `Buffer<T, A>` with the specified capacity
    /// using the provided allocator.
    ///
    /// The buffer will be able to hold exactly `capacity` elements. For non-CPU
    /// backends, this capacity is fixed and cannot be exceeded. Attempting to
    /// add more elements than the capacity will result in a panic.
    ///
    /// # Panics
    ///
    /// Panics if the new capacity exceeds `isize::MAX` bytes.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use crate::{Buffer, CpuBackend, GLOBAL_CPU_BACKEND};
    ///
    /// let mut buffer = Buffer::with_capacity_in(10, GLOBAL_CPU_BACKEND);
    ///
    /// // The buffer contains no items, even though it has capacity for more
    /// assert_eq!(buffer.len(), 0);
    /// assert_eq!(buffer.capacity(), 10);
    /// ```
    #[inline]
    #[must_use]
    pub fn with_capacity_in(capacity: usize, allocator: A) -> Self {
        let buf = RawBuffer::with_capacity_in(capacity, allocator);
        Self { buf, len: 0 }
    }

    /// Tries to construct a new, empty `Buffer<T, A>` with the specified
    /// capacity using the provided allocator.
    ///
    /// This is the fallible version of [`with_capacity_in`]. It returns an error
    /// if the allocation fails instead of panicking.
    ///
    /// # Errors
    ///
    /// Returns `Err(TryReserveError)` if the allocator fails to allocate memory.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use crate::{Buffer, CpuBackend, GLOBAL_CPU_BACKEND};
    ///
    /// match Buffer::<i32, CpuBackend>::try_with_capacity_in(10, GLOBAL_CPU_BACKEND) {
    ///     Ok(buffer) => {
    ///         assert_eq!(buffer.len(), 0);
    ///         assert_eq!(buffer.capacity(), 10);
    ///     }
    ///     Err(e) => println!("Failed to allocate: {:?}", e),
    /// }
    /// ```
    ///
    /// [`with_capacity_in`]: Buffer::with_capacity_in
    #[inline]
    pub fn try_with_capacity_in(capacity: usize, allocator: A) -> Result<Self, TryReserveError> {
        let buf = RawBuffer::try_with_capacity_in(capacity, allocator)?;
        Ok(Self { buf, len: 0 })
    }

    /// Returns a new buffer from a pointer, length, and capacity.
    ///
    /// # Safety
    ///
    /// The pointer must be valid, it must have allocated memory in the size of
    /// capacity * size_of<T>, and the first `len` elements of the buffer must be initialized or
    /// about to be initialized in a foreign call.
    pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize, alloc: A) -> Self {
        Self { buf: RawBuffer::from_raw_parts_in(ptr, capacity, alloc), len: length }
    }

    /// Returns the number of elements in the buffer, also referred to as its 'length'.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let buffer = buffer![1, 2, 3];
    /// assert_eq!(buffer.len(), 3);
    /// ```
    #[inline]
    pub fn len(&self) -> usize {
        self.len
    }

    /// Returns the total number of elements the buffer can hold.
    ///
    /// For non-CPU backends, this is a fixed value that cannot change.
    /// For CPU backends, this may increase if operations like `push` or
    /// `extend` trigger internal reallocation through `Vec` conversion.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let buffer: Buffer<i32> = Buffer::with_capacity(10);
    /// assert_eq!(buffer.capacity(), 10);
    /// ```
    #[inline]
    pub fn capacity(&self) -> usize {
        self.buf.capacity()
    }

    /// # Safety
    ///
    /// This function is unsafe because it enables bypassing the lifetime of the buffer.
    #[inline]
    pub unsafe fn owned_unchecked(&self) -> ManuallyDrop<Self> {
        self.owned_unchecked_in(self.allocator().clone())
    }

    /// # Safety
    ///
    /// This function is unsafe because it enables bypassing the lifetime of the buffer.
    #[inline]
    pub unsafe fn owned_unchecked_in(&self, allocator: A) -> ManuallyDrop<Self> {
        let ptr = self.as_ptr() as *mut T;
        let len = self.len();
        let cap = self.capacity();
        ManuallyDrop::new(Self::from_raw_parts(ptr, len, cap, allocator))
    }

    /// Returns `true` if the buffer contains no elements.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let mut buffer = Buffer::with_capacity(10);
    /// assert!(buffer.is_empty());
    ///
    /// buffer.push(1);
    /// assert!(!buffer.is_empty());
    /// ```
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Returns a raw pointer to the buffer's elements.
    ///
    /// The caller must ensure that the buffer outlives the pointer this function
    /// returns, or else it will end up pointing to garbage. For CPU backends,
    /// modifying the buffer may cause its buffer to be reallocated, which would
    /// also make any pointers to it invalid.
    ///
    /// The pointer is valid for reads of up to `len() * size_of::<T>()` bytes.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let buffer = buffer![1, 2, 4];
    /// let buffer_ptr = buffer.as_ptr();
    ///
    /// unsafe {
    ///     for i in 0..buffer.len() {
    ///         assert_eq!(*buffer_ptr.add(i), [1, 2, 4][i]);
    ///     }
    /// }
    /// ```
    #[inline]
    pub fn as_ptr(&self) -> *const T {
        self.buf.ptr()
    }

    /// Returns an unsafe mutable pointer to the buffer's elements.
    ///
    /// The caller must ensure that the buffer outlives the pointer this function
    /// returns, or else it will end up pointing to garbage. For CPU backends,
    /// modifying the buffer may cause its buffer to be reallocated, which would
    /// also make any pointers to it invalid.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let mut buffer = buffer![1, 2, 4];
    /// let buffer_ptr = buffer.as_mut_ptr();
    ///
    /// unsafe {
    ///     for i in 0..buffer.len() {
    ///         *buffer_ptr.add(i) = i as i32;
    ///     }
    /// }
    ///
    /// assert_eq!(&*buffer, &[0, 1, 2]);
    /// ```
    #[inline]
    pub fn as_mut_ptr(&mut self) -> *mut T {
        self.buf.ptr()
    }

    /// Forces the length of the buffer to `new_len`.
    ///
    /// This is a low-level operation that maintains none of the normal invariants
    /// of the type. Normally changing the length of a buffer is done using one of
    /// the safe operations instead, such as [`push`], [`pop`], [`extend_from_slice`],
    /// or [`clear`].
    ///
    /// # Safety
    ///
    /// - `new_len` must be less than or equal to [`capacity()`].
    /// - The elements at `old_len..new_len` must be initialized.
    ///
    /// # Examples
    ///
    /// This method can be useful for situations in which the buffer is serving as a
    /// buffer for other code, particularly over FFI. As an example, if FFI code writes
    /// values into the buffer, then this can be used to change the length of the buffer
    /// to match the number of elements written.
    ///
    /// ```rust,ignore
    /// let mut buffer = Buffer::with_capacity(3);
    /// unsafe {
    ///     let ptr = buffer.as_mut_ptr();
    ///     // Overwrite memory with 3, 2, 1
    ///     ptr.write(3);
    ///     ptr.add(1).write(2);
    ///     ptr.add(2).write(1);
    ///
    ///     // Set the length to 3 after writing
    ///     buffer.set_len(3);
    /// }
    /// assert_eq!(&*buffer, &[3, 2, 1]);
    /// ```
    ///
    /// [`capacity()`]: Buffer::capacity
    /// [`push`]: Buffer::push
    /// [`pop`]: Buffer::pop
    /// [`extend_from_slice`]: Buffer::extend_from_slice
    /// [`clear`]: Buffer::clear
    #[inline]
    pub unsafe fn set_len(&mut self, new_len: usize) {
        self.len = new_len;
    }

    /// Assumes that the entire capacity of the buffer is initialized.
    ///
    /// This sets the buffer's length to its capacity, effectively marking all
    /// allocated memory as containing valid values of type `T`.
    ///
    /// # Safety
    ///
    /// The caller must ensure that all elements up to the buffer's capacity are
    /// properly initialized before calling this method. Calling this on a buffer
    /// with uninitialized memory will lead to undefined behavior when those
    /// elements are accessed.
    ///
    /// This is particularly dangerous for types with drop implementations, as
    /// dropping uninitialized memory can cause crashes or worse.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let mut buffer: Buffer<u8> = Buffer::with_capacity(4);
    ///
    /// unsafe {
    ///     // Initialize all 4 bytes
    ///     buffer.as_mut_ptr().write_bytes(0, 4);
    ///     
    ///     // Now we can safely assume all memory is initialized
    ///     buffer.assume_init();
    /// }
    ///
    /// assert_eq!(buffer.len(), 4);
    /// assert_eq!(&*buffer, &[0, 0, 0, 0]);
    /// ```
    #[inline]
    pub unsafe fn assume_init(&mut self) {
        let cap = self.capacity();
        self.set_len(cap);
    }

    /// Copies all elements from `src` into `self`, using `copy_nonoverlapping`.
    ///
    /// The length of `src` must be the same as `self`. This method overwrites the
    /// entire contents of the buffer.
    ///
    /// # Panics
    ///
    /// This function will panic if the two slices have different lengths.
    ///
    /// # Errors
    ///
    /// Returns `Err(CopyError)` if the allocator fails to perform the copy operation.
    ///
    /// # Safety
    ///
    /// This operation is potentially asynchronous. The caller must ensure the memory
    /// of the source slice remains valid for the duration of the operation. For backends
    /// that perform asynchronous operations (like GPU backends), the source memory must
    /// not be freed or modified until the operation completes.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let mut buffer = Buffer::with_capacity(3);
    /// unsafe {
    ///     buffer.set_len(3); // Must set length first
    ///     buffer.copy_from_host_slice(&[1, 2, 3]).unwrap();
    /// }
    /// assert_eq!(&*buffer, &[1, 2, 3]);
    /// ```
    #[track_caller]
    pub unsafe fn copy_from_host_slice(&mut self, src: &[T]) -> Result<(), CopyError> {
        // The panic code path was put into a cold function to not bloat the
        // call site.
        #[inline(never)]
        #[cold]
        #[track_caller]
        fn len_mismatch_fail(dst_len: usize, src_len: usize) -> ! {
            panic!(
                "source slice length ({src_len}) does not match destination slice length ({dst_len})",
            );
        }

        if self.len() != src.len() {
            len_mismatch_fail(self.len(), src.len());
        }

        let layout = Layout::array::<T>(src.len()).unwrap();

        unsafe {
            self.buf.allocator().copy_nonoverlapping(
                src.as_ptr() as *const u8,
                self.buf.ptr() as *mut u8,
                layout.size(),
                CopyDirection::HostToDevice,
            )
        }
    }

    /// Returns a reference to the underlying allocator.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use crate::{Buffer, CpuBackend, GLOBAL_CPU_BACKEND};
    ///
    /// let buffer: Buffer<i32, CpuBackend> = Buffer::with_capacity(10);
    /// let allocator = buffer.allocator();
    /// // Can use the allocator reference for other operations
    /// ```
    #[inline]
    pub fn allocator(&self) -> &A {
        self.buf.allocator()
    }

    /// Returns a mutable reference to the underlying allocator.
    ///
    /// # Safety
    ///
    /// This method is unsafe because modifying the allocator while the buffer
    /// is in use could lead to undefined behavior. The caller must ensure that
    /// any modifications to the allocator do not invalidate the buffer's
    /// existing allocations or violate any invariants.
    #[inline]
    pub unsafe fn allocator_mut(&mut self) -> &mut A {
        self.buf.allocator_mut()
    }

    /// Appends all elements from a device slice into `self`.
    ///
    /// This extends the buffer by copying elements from another slice on the same device.
    /// The operation uses `copy_nonoverlapping` and is typically more efficient than
    /// host-to-device copies.
    ///
    /// # Panics
    ///
    /// This function will panic if the resulting length exceeds the buffer's capacity.
    ///
    /// # Errors
    ///
    /// Returns `Err(CopyError)` if the allocator fails to perform the copy operation.
    ///
    /// # Safety
    ///
    /// While this method is safe to call, the operation may be asynchronous depending
    /// on the backend. The implementation ensures proper memory handling.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let mut buffer1 = buffer![1, 2, 3];
    /// let mut buffer2 = Buffer::with_capacity(6);
    ///
    /// // Copy elements from buffer1 to buffer2
    /// buffer2.extend_from_device_slice(&buffer1[..]).unwrap();
    /// assert_eq!(buffer2.len(), 3);
    /// ```
    #[track_caller]
    pub fn extend_from_device_slice(&mut self, src: &Slice<T, A>) -> Result<(), CopyError> {
        // The panic code path was put into a cold function to not bloat the
        // call site.
        #[inline(never)]
        #[cold]
        #[track_caller]
        fn capacity_fail(dst_len: usize, src_len: usize, cap: usize) -> ! {
            panic!(
                "source slice length ({src_len}) too long for buffer of length ({dst_len}) and capacity ({cap})"
            );
        }

        if self.len() + src.len() > self.capacity() {
            capacity_fail(self.len(), src.len(), self.capacity());
        }

        let layout = Layout::array::<T>(src.len()).unwrap();

        unsafe {
            self.buf.allocator().copy_nonoverlapping(
                src.as_ptr() as *const u8,
                self.buf.ptr().add(self.len()) as *mut u8,
                layout.size(),
                CopyDirection::DeviceToDevice,
            )?;
        }

        // Extend the length of the buffer to include the new elements.
        self.len += src.len();

        Ok(())
    }

    /// Appends all elements from a host slice into `self`.
    ///
    /// This extends the buffer by copying elements from CPU memory. For non-CPU backends,
    /// this involves a host-to-device transfer.
    ///
    /// # Panics
    ///
    /// This function will panic if the resulting length exceeds the buffer's capacity.
    ///
    /// # Errors
    ///
    /// Returns `Err(CopyError)` if the allocator fails to perform the copy operation.
    ///
    /// # Safety
    ///
    /// While this method is safe to call, the operation may be asynchronous depending
    /// on the backend. The implementation ensures the source memory remains valid
    /// during the operation.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let mut buffer = Buffer::with_capacity(5);
    /// buffer.extend_from_host_slice(&[1, 2, 3]).unwrap();
    /// assert_eq!(buffer.len(), 3);
    ///
    /// buffer.extend_from_host_slice(&[4, 5]).unwrap();
    /// assert_eq!(buffer.len(), 5);
    /// ```
    #[track_caller]
    pub fn extend_from_host_slice(&mut self, src: &[T]) -> Result<(), CopyError> {
        // The panic code path was put into a cold function to not bloat the
        // call site.
        #[inline(never)]
        #[cold]
        #[track_caller]
        fn capacity_fail(dst_len: usize, src_len: usize, cap: usize) -> ! {
            panic!(
                "source slice length ({src_len}) too long for buffer of length ({dst_len}) and capacity ({cap})"
            );
        }

        if self.len() + src.len() > self.capacity() {
            capacity_fail(self.len(), src.len(), self.capacity());
        }

        let layout = Layout::array::<T>(src.len()).unwrap();

        unsafe {
            self.buf.allocator().copy_nonoverlapping(
                src.as_ptr() as *const u8,
                self.buf.ptr().add(self.len()) as *mut u8,
                layout.size(),
                CopyDirection::HostToDevice,
            )?;
        }

        // Extend the length of the buffer to include the new elements.
        self.len += src.len();

        Ok(())
    }

    /// Copies all elements from `self` into `dst`, using `copy_nonoverlapping`.
    ///
    /// The length of `dst` must be the same as `self`.
    ///
    /// **Note**: This function might be blocking.
    ///
    /// # Safety
    ///
    /// This operation is potentially asynchronous. The caller must insure the memory of the
    /// destination is valid for the duration of the operation.
    #[track_caller]
    pub unsafe fn copy_into_host(&self, dst: &mut [MaybeUninit<T>]) -> Result<(), CopyError> {
        // The panic code path was put into a cold function to not bloat the
        // call site.
        #[inline(never)]
        #[cold]
        #[track_caller]
        fn len_mismatch_fail(dst_len: usize, src_len: usize) -> ! {
            panic!(
                "source slice length ({src_len}) does not match destination slice length ({dst_len})",
            );
        }

        if self.len() != dst.len() {
            len_mismatch_fail(dst.len(), self.len());
        }

        let layout = Layout::array::<T>(dst.len()).unwrap();

        unsafe {
            self.buf.allocator().copy_nonoverlapping(
                self.buf.ptr() as *const u8,
                dst.as_mut_ptr() as *mut u8,
                layout.size(),
                CopyDirection::DeviceToHost,
            )
        }
    }

    /// Copies all elements from `self` into a newely allocated [Vec<T>] and returns it.
    ///
    /// # Safety
    ///  See [Buffer::copy_into_host]
    pub unsafe fn copy_into_host_vec(&self) -> Vec<T> {
        let mut vec = Vec::with_capacity(self.len());
        self.copy_into_host(vec.spare_capacity_mut()).unwrap();
        unsafe {
            vec.set_len(self.len());
        }
        vec
    }

    /// Copies all elements from `self` into a newely allocated [Vec<T>] and returns it.
    ///
    /// # Safety
    ///  See [Buffer::copy_into_host]
    pub unsafe fn copy_into_host_buffer(&self) -> Buffer<T, CpuBackend> {
        let vec = self.copy_into_host_vec();
        Buffer::from(vec)
    }

    /// Sets `len` bytes of memory starting at the current length to `value`.
    ///
    /// This extends the buffer by `len` bytes, all set to `value`. The `len`
    /// parameter must be a multiple of `size_of::<T>()` to ensure proper alignment.
    ///
    /// # Errors
    ///
    /// Returns `Err(CopyError)` if the backend allocator fails to perform the
    /// memory operation.
    ///
    /// # Panics
    ///
    /// - Panics if `len` is not a multiple of `size_of::<T>()`
    /// - Panics if extending by `len` bytes would exceed the buffer's capacity
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let mut buffer: Buffer<u32> = Buffer::with_capacity(10);
    ///
    /// // Write 12 bytes (3 u32s) of value 0xFF
    /// buffer.write_bytes(0xFF, 12).unwrap();
    /// assert_eq!(buffer.len(), 3);
    /// assert_eq!(*buffer[0], 0xFFFFFFFF);
    /// ```
    #[track_caller]
    pub fn write_bytes(&mut self, value: u8, len: usize) -> Result<(), CopyError> {
        // The panic code path was put into a cold function to not bloat the
        // call site.
        #[inline(never)]
        #[cold]
        #[track_caller]
        fn capacity_fail(dst_len: usize, len: usize, cap: usize) -> ! {
            panic!("Cannot write {len} bytes to buffer of length {dst_len} and capacity {cap}");
        }

        // The panic code path was put into a cold function to not bloat the
        // call site.
        #[inline(never)]
        #[cold]
        #[track_caller]
        fn align_fail(len: usize, size: usize) -> ! {
            panic!("Number of bytes ({len}) does not match the size of the type ({size})");
        }

        // Check that the number of bytes matches the size of the type.
        if !len.is_multiple_of(std::mem::size_of::<T>()) {
            align_fail(len, std::mem::size_of::<T>());
        }

        // Check that the buffer has enough capacity.
        if self.len() * std::mem::size_of::<T>() + len > self.capacity() * std::mem::size_of::<T>()
        {
            capacity_fail(self.len(), len, self.capacity());
        }

        // Write the bytes to the buffer.
        unsafe {
            self.buf.allocator().write_bytes(
                self.buf.ptr().add(self.len()) as *mut u8,
                value,
                len,
            )?;
        }

        // Extend the length of the buffer to include the new elements.
        self.len += len / std::mem::size_of::<T>();

        Ok(())
    }

    /// Reinterprets the buffer's elements as base field elements.
    ///
    /// This method consumes the buffer and returns a new buffer where each
    /// extension field element is reinterpreted as `D` base field elements,
    /// where `D` is the degree of the extension.
    ///
    /// # Type Parameters
    ///
    /// - `E`: The base field type
    /// - `T`: Must implement `ExtensionField<E>`
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// // If T is a degree-4 extension over E
    /// let buffer: Buffer<ExtField> = buffer![ext1, ext2, ext3];
    /// let base_buffer: Buffer<BaseField> = buffer.flatten_to_base();
    /// assert_eq!(base_buffer.len(), 12); // 3 * 4 = 12
    /// ```
    pub fn flatten_to_base<E>(self) -> Buffer<E, A>
    where
        T: ExtensionField<E>,
        E: Field,
    {
        let mut buffer = ManuallyDrop::new(self);
        let (original_ptr, original_len, original_cap, allocator) =
            (buffer.as_mut_ptr(), buffer.len(), buffer.capacity(), buffer.allocator().clone());
        let ptr = original_ptr as *mut E;
        let len = original_len * T::D;
        let cap = original_cap * T::D;
        unsafe { Buffer::from_raw_parts(ptr, len, cap, allocator) }
    }

    /// Reinterprets the buffer's base field elements as extension field elements.
    ///
    /// This method consumes the buffer and returns a new buffer where every `D`
    /// base field elements are reinterpreted as one extension field element,
    /// where `D` is the degree of the extension.
    ///
    /// # Type Parameters
    ///
    /// - `T`: The base field type
    /// - `E`: Must implement `ExtensionField<T>`
    ///
    /// # Panics
    ///
    /// Panics if the buffer length is not divisible by the extension degree.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// // If E is a degree-4 extension over T
    /// let buffer: Buffer<BaseField> = buffer![b1, b2, b3, b4, b5, b6, b7, b8];
    /// let ext_buffer: Buffer<ExtField> = buffer.into_extension();
    /// assert_eq!(ext_buffer.len(), 2); // 8 / 4 = 2
    /// ```
    pub fn into_extension<E>(self) -> Buffer<E, A>
    where
        T: Field,
        E: ExtensionField<T>,
    {
        let mut buffer = ManuallyDrop::new(self);
        let (original_ptr, original_len, original_cap, allocator) =
            (buffer.as_mut_ptr(), buffer.len(), buffer.capacity(), buffer.allocator().clone());
        let ptr = original_ptr as *mut E;
        let len = original_len.checked_div(E::D).unwrap();
        let cap = original_cap.checked_div(E::D).unwrap();
        unsafe { Buffer::from_raw_parts(ptr, len, cap, allocator) }
    }
}

impl<T, A: Backend> HasBackend for Buffer<T, A> {
    type Backend = A;

    fn backend(&self) -> &Self::Backend {
        self.buf.allocator()
    }
}

impl<T> Buffer<T, CpuBackend> {
    /// Constructs a new, empty `Buffer<T>` with at least the specified capacity.
    ///
    /// This is a convenience method that uses the global CPU backend allocator.
    /// The buffer will be able to hold at least `capacity` elements without
    /// reallocating. If `capacity` is 0, the buffer will not allocate.
    ///
    /// Note that for CPU backend buffers, the capacity can grow beyond the initial
    /// value through operations like `push` or `extend_from_slice`.
    ///
    /// # Panics
    ///
    /// Panics if the new capacity exceeds `isize::MAX` bytes.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let mut buffer = Buffer::with_capacity(10);
    /// assert!(buffer.capacity() >= 10);
    /// ```
    #[inline]
    pub fn with_capacity(capacity: usize) -> Self {
        Self::with_capacity_in(capacity, GLOBAL_CPU_BACKEND)
    }

    /// Appends an element to the back of the buffer.
    ///
    /// For CPU backend buffers, this may cause reallocation if the buffer is full.
    /// The reallocation is handled by converting to/from `Vec<T>` internally.
    ///
    /// # Panics
    ///
    /// Panics if the new capacity exceeds `isize::MAX` bytes.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let mut buffer = Buffer::with_capacity(2);
    /// buffer.push(3);
    /// assert_eq!(&*buffer, &[3]);
    ///
    /// buffer.push(4);
    /// assert_eq!(&*buffer, &[3, 4]);
    ///
    /// // This will trigger reallocation
    /// buffer.push(5);
    /// assert_eq!(&*buffer, &[3, 4, 5]);
    /// assert!(buffer.capacity() >= 3);
    /// ```
    #[inline]
    pub fn push(&mut self, value: T) {
        let take_self = std::mem::take(self);
        let mut vec = Vec::from(take_self);
        vec.push(value);
        *self = Self::from(vec);
    }

    /// Removes the last element from the buffer and returns it, or `None` if empty.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let mut buffer = buffer![1, 2, 3];
    /// assert_eq!(buffer.pop(), Some(3));
    /// assert_eq!(&*buffer, &[1, 2]);
    /// assert_eq!(buffer.pop(), Some(2));
    /// assert_eq!(buffer.pop(), Some(1));
    /// assert_eq!(buffer.pop(), None);
    /// ```
    #[inline]
    pub fn pop(&mut self) -> Option<T> {
        if self.is_empty() {
            return None;
        }

        // This is safe because we have just checked that the buffer is not empty.
        unsafe {
            let len = self.len();
            let ptr = &mut self[len - 1] as *mut _ as *mut T;
            let value = ptr.read();
            self.set_len(len - 1);
            Some(value)
        }
    }

    /// Clears the buffer, removing all values.
    ///
    /// Note that this method has no effect on the allocated capacity of the buffer.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let mut buffer = buffer![1, 2, 3];
    /// buffer.clear();
    /// assert!(buffer.is_empty());
    /// assert!(buffer.capacity() >= 3);
    /// ```
    #[inline]
    pub fn clear(&mut self) {
        let elems: *mut [T] = self.as_mut_slice();

        // SAFETY:
        // - `elems` comes directly from `as_mut_slice` and is therefore valid.
        // - Setting `self.len` before calling `drop_in_place` means that, if an element's `Drop`
        //   impl panics, the vector's `Drop` impl will do nothing (leaking the rest of the
        //   elements) instead of dropping some twice.
        unsafe {
            self.len = 0;
            std::ptr::drop_in_place(elems);
        }
    }

    /// Resizes the buffer in-place so that `len` is equal to `new_len`.
    ///
    /// If `new_len` is greater than `len`, the buffer is extended by the
    /// difference, with each additional slot filled with `value`.
    /// If `new_len` is less than `len`, the buffer is simply truncated.
    ///
    /// This method may trigger reallocation if `new_len` exceeds the current capacity.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let mut buffer = buffer![1, 2, 3];
    /// buffer.resize(5, 0);
    /// assert_eq!(&*buffer, &[1, 2, 3, 0, 0]);
    ///
    /// buffer.resize(2, 0);
    /// assert_eq!(&*buffer, &[1, 2]);
    /// ```
    #[inline]
    pub fn resize(&mut self, new_len: usize, value: T)
    where
        T: Copy,
    {
        let owned_self = std::mem::take(self);
        let mut vec = Vec::from(owned_self);
        vec.resize(new_len, value);
        *self = Self::from(vec);
    }

    /// Extends the buffer with the contents of the given slice.
    ///
    /// This is a specialized version for CPU backend that can trigger reallocation
    /// if needed to accommodate the new elements.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let mut buffer = buffer![1, 2, 3];
    /// buffer.extend_from_slice(&[4, 5, 6]);
    /// assert_eq!(&*buffer, &[1, 2, 3, 4, 5, 6]);
    /// ```
    #[inline]
    pub fn extend_from_slice(&mut self, slice: &[T]) {
        // Check to see if capacity needs to be increased.
        if self.len() + slice.len() > self.capacity() {
            let additional_capacity = self.len() + slice.len() - self.capacity();
            let owned_self = std::mem::take(self);
            let mut vec = Vec::from(owned_self);
            vec.reserve(vec.capacity() + additional_capacity);
            *self = Self::from(vec);
            assert!(self.capacity() >= self.len() + slice.len());
        }

        self.extend_from_host_slice(slice).unwrap()
    }

    /// Converts the buffer into a `Vec<T>`.
    ///
    /// This consumes the buffer and transfers ownership of its data to a standard
    /// `Vec`. This is a zero-cost operation as the underlying memory layout is
    /// compatible.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let buffer = buffer![1, 2, 3];
    /// let vec = buffer.into_vec();
    /// assert_eq!(vec, vec![1, 2, 3]);
    /// ```
    #[inline]
    pub fn into_vec(self) -> Vec<T> {
        self.into()
    }

    /// Returns a slice containing the entire buffer.
    ///
    /// Equivalent to `&buffer[..]`.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let buffer = buffer![1, 2, 3];
    /// assert_eq!(buffer.as_slice(), &[1, 2, 3]);
    /// ```
    #[inline]
    pub fn as_slice(&self) -> &[T] {
        &self[..]
    }

    /// Returns a mutable slice containing the entire buffer.
    ///
    /// Equivalent to `&mut buffer[..]`.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let mut buffer = buffer![1, 2, 3];
    /// buffer.as_mut_slice()[0] = 7;
    /// assert_eq!(&*buffer, &[7, 2, 3]);
    /// ```
    #[inline]
    pub fn as_mut_slice(&mut self) -> &mut [T] {
        &mut self[..]
    }

    /// Returns the remaining spare capacity of the buffer as a slice of `MaybeUninit<T>`.
    ///
    /// The returned slice can be used to fill the buffer with data before marking
    /// the data as initialized using [`set_len`].
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let mut buffer = Buffer::with_capacity(10);
    /// buffer.push(0);
    /// buffer.push(1);
    ///
    /// let spare = buffer.spare_capacity_mut();
    /// assert_eq!(spare.len(), 8);
    ///
    /// // Initialize the spare capacity
    /// for i in 0..4 {
    ///     spare[i].write(i as i32 + 2);
    /// }
    ///
    /// unsafe {
    ///     buffer.set_len(6);
    /// }
    /// assert_eq!(&*buffer, &[0, 1, 2, 3, 4, 5]);
    /// ```
    ///
    /// [`set_len`]: Buffer::set_len
    pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
        let mut vec = ManuallyDrop::new(unsafe {
            Vec::from_raw_parts(self.as_mut_ptr(), self.len(), self.capacity())
        });
        let slice = vec.spare_capacity_mut();
        let len = slice.len();
        let ptr = slice.as_mut_ptr();
        unsafe { std::slice::from_raw_parts_mut(ptr, len) }
    }

    /// Inserts an element at position `index`, shifting all elements after it to the right.
    ///
    /// This operation may trigger reallocation if the buffer is at capacity.
    ///
    /// # Panics
    ///
    /// Panics if `index > len`.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let mut buffer = buffer![1, 2, 3];
    /// buffer.insert(1, 4);
    /// assert_eq!(&*buffer, &[1, 4, 2, 3]);
    /// buffer.insert(4, 5);
    /// assert_eq!(&*buffer, &[1, 4, 2, 3, 5]);
    /// ```
    #[inline]
    pub fn insert(&mut self, index: usize, value: T) {
        let take_self = std::mem::take(self);
        let mut vec = Vec::from(take_self);
        vec.insert(index, value);
        *self = Self::from(vec);
    }
}

impl<T> From<Vec<T>> for Buffer<T, CpuBackend> {
    /// Creates a buffer from a `Vec<T>`.
    ///
    /// This is a zero-cost conversion that takes ownership of the vector's
    /// allocated memory.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let vec = vec![1, 2, 3, 4];
    /// let buffer = Buffer::from(vec);
    /// assert_eq!(&*buffer, &[1, 2, 3, 4]);
    /// ```
    fn from(value: Vec<T>) -> Self {
        unsafe {
            let mut vec = ManuallyDrop::new(value);
            Buffer::from_raw_parts(vec.as_mut_ptr(), vec.len(), vec.capacity(), GLOBAL_CPU_BACKEND)
        }
    }
}

impl<T> Default for Buffer<T, CpuBackend> {
    /// Creates an empty buffer.
    ///
    /// Equivalent to `Buffer::with_capacity(0)`.
    #[inline]
    fn default() -> Self {
        Self::with_capacity(0)
    }
}

impl<T> From<Buffer<T, CpuBackend>> for Vec<T> {
    /// Converts a buffer into a `Vec<T>`.
    ///
    /// This is a zero-cost conversion that transfers ownership of the buffer's
    /// allocated memory to the vector.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let buffer = buffer![1, 2, 3];
    /// let vec = Vec::from(buffer);
    /// assert_eq!(vec, vec![1, 2, 3]);
    /// ```
    fn from(value: Buffer<T, CpuBackend>) -> Self {
        let mut self_undropped = ManuallyDrop::new(value);
        unsafe {
            Vec::from_raw_parts(
                self_undropped.as_mut_ptr(),
                self_undropped.len(),
                self_undropped.capacity(),
            )
        }
    }
}

impl<T> FromIterator<T> for Buffer<T, CpuBackend> {
    /// Creates a buffer from an iterator.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let buffer: Buffer<_> = (0..5).collect();
    /// assert_eq!(&*buffer, &[0, 1, 2, 3, 4]);
    ///
    /// let buffer: Buffer<_> = vec![1, 2, 3].into_iter().collect();
    /// assert_eq!(&*buffer, &[1, 2, 3]);
    /// ```
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        let vec: Vec<T> = iter.into_iter().collect();
        Self::from(vec)
    }
}

/// Creates a [`Buffer`] containing the arguments.
///
/// `buffer!` allows creating buffers using the same syntax as the `vec!` macro.
/// It simply creates a `Vec` and converts it to a `Buffer`.
///
/// # Examples
///
/// ```rust,ignore
/// let buffer = buffer![1, 2, 3];
/// assert_eq!(&*buffer, &[1, 2, 3]);
///
/// let buffer = buffer![0; 5];
/// assert_eq!(&*buffer, &[0, 0, 0, 0, 0]);
/// ```
///
/// [`Buffer`]: crate::Buffer
#[macro_export]
macro_rules! buffer {
    ($($x:expr),*) => {
       $crate::Buffer::from(vec![$($x),*])
    };
}

macro_rules! impl_index {
    ($($t:ty)*) => {
        $(
            impl<T, A: Backend> Index<$t> for Buffer<T, A>
            {
                type Output = Slice<T, A>;

                fn index(&self, index: $t) -> &Slice<T, A> {
                    unsafe {
                        Slice::from_slice(
                         std::slice::from_raw_parts(self.as_ptr(), self.len).index(index)
                    )
                  }
                }
            }

            impl<T, A: Backend> IndexMut<$t> for Buffer<T, A>
            {
                fn index_mut(&mut self, index: $t) -> &mut Slice<T, A> {
                    unsafe {
                        Slice::from_slice_mut(
                            std::slice::from_raw_parts_mut(self.as_mut_ptr(), self.len).index_mut(index)
                        )
                    }
                }
            }
        )*
    }
}

impl_index! {
    Range<usize>
    RangeFull
    RangeFrom<usize>
    RangeInclusive<usize>
    RangeTo<usize>
    RangeToInclusive<usize>
}

impl<T, A: Backend> Deref for Buffer<T, A> {
    type Target = Slice<T, A>;

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

impl<T, A: Backend> DerefMut for Buffer<T, A> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self[..]
    }
}

impl<T, A: Backend> Index<usize> for Buffer<T, A> {
    type Output = Init<T, A>;

    #[inline]
    fn index(&self, index: usize) -> &Self::Output {
        &self[..][index]
    }
}

impl<T, A: Backend> IndexMut<usize> for Buffer<T, A> {
    #[inline]
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        &mut self[..][index]
    }
}

impl<T, A: Backend> Clone for Buffer<T, A> {
    /// Returns a copy of the buffer.
    ///
    /// This allocates a new buffer with the same capacity as `self` and copies
    /// all elements using the backend's `copy_nonoverlapping` operation.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let buffer1 = buffer![1, 2, 3];
    /// let buffer2 = buffer1.clone();
    /// assert_eq!(&*buffer1, &*buffer2);
    /// ```
    #[inline]
    fn clone(&self) -> Self {
        let mut cloned = Self::with_capacity_in(self.len(), self.allocator().clone());
        let layout = Layout::array::<T>(self.len()).unwrap();
        unsafe {
            self.buf
                .allocator()
                .copy_nonoverlapping(
                    self.as_ptr() as *const u8,
                    cloned.as_mut_ptr() as *mut u8,
                    layout.size(),
                    CopyDirection::DeviceToDevice,
                )
                .unwrap();
            cloned.set_len(self.len());
        }
        cloned
    }
}

impl<T: PartialEq> PartialEq for Buffer<T, CpuBackend> {
    /// Tests for equality between two buffers.
    ///
    /// Two buffers are considered equal if the underlying slices are equal, i.e. they have the same
    /// length and all corresponding elements are equal. Capacity is not considered.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let buffer1 = buffer![1, 2, 3];
    /// let buffer2 = buffer![1, 2, 3];
    /// assert_eq!(buffer1, buffer2);
    ///
    /// let buffer3 = buffer![1, 2, 4];
    /// assert_ne!(buffer1, buffer3);
    /// ```
    fn eq(&self, other: &Self) -> bool {
        self[..] == other[..]
    }
}

impl<T: Eq> Eq for Buffer<T, CpuBackend> {}

impl<T: Serialize> Serialize for Buffer<T, CpuBackend> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.as_slice().serialize(serializer)
    }
}

impl<'de, T: Deserialize<'de>> Deserialize<'de> for Buffer<T, CpuBackend> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let vec: Vec<T> = Vec::deserialize(deserializer)?;
        Ok(Buffer::from(vec))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_buffer() {
        let mut buffer = Buffer::<u32>::with_capacity(10);
        assert_eq!(buffer.len(), 0);
        assert_eq!(buffer.capacity(), 10);

        buffer.push(1);
        buffer.push(2);
        buffer.push(3);
        assert_eq!(buffer.len(), 3);

        let as_slice: &[u32] = &buffer[..];
        assert_eq!(as_slice, &[1, 2, 3]);

        let val = *buffer[0];
        assert_eq!(val, 1);

        let val = *buffer[1];
        assert_eq!(val, 2);

        let val = *buffer[2];
        assert_eq!(val, 3);

        let value = buffer.pop().unwrap();
        assert_eq!(value, 3);
        assert_eq!(buffer.len(), 2);

        buffer.extend_from_slice(&[4, 5, 6]);
        let host_vec = Vec::from(buffer);
        assert_eq!(host_vec, [1, 2, 4, 5, 6]);

        // Test the host_buffer!() macro
        let buffer = buffer![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
        assert_eq!(buffer.len(), 10);
        assert_eq!(buffer.capacity(), 10);
        assert_eq!(*buffer[0], 1);
        assert_eq!(*buffer[1], 2);
        assert_eq!(*buffer[2], 3);
        assert_eq!(*buffer[3], 4);
        assert_eq!(*buffer[4], 5);
        assert_eq!(*buffer[5], 6);
        assert_eq!(*buffer[6], 7);
        assert_eq!(*buffer[7], 8);
        assert_eq!(*buffer[8], 9);
        assert_eq!(*buffer[9], 10);

        let mut buffer = buffer![1, 2, 3, 4, 5, 6, 7, 8, 9];
        buffer.insert(0, 0);
        assert_eq!(buffer.len(), 10);
        assert_eq!(*buffer[0], 0);
        assert_eq!(*buffer[1], 1);
        assert_eq!(*buffer[2], 2);
        assert_eq!(*buffer[3], 3);
        assert_eq!(*buffer[4], 4);
        buffer.insert(4, 4);
        assert_eq!(buffer.len(), 11);
        assert_eq!(*buffer[4], 4);
        assert_eq!(*buffer[5], 4);
    }
}