1use core::mem::MaybeUninit;
5use std::alloc::Layout;
6use std::any::type_name;
7use std::cmp::max;
8use std::fmt::Debug;
9use std::fmt::Formatter;
10use std::ops::Deref;
11use std::ops::DerefMut;
12
13use itertools::Itertools;
14use vortex_error::VortexExpect;
15use vortex_error::vortex_panic;
16
17use crate::Alignment;
18use crate::Allocation;
19use crate::Buffer;
20use crate::BufferAllocatorRef;
21use crate::ByteBufferMut;
22use crate::debug::TruncatedDebug;
23use crate::trusted_len::TrustedLen;
24
25pub struct BufferMut<T> {
39 pub(crate) allocation: Allocation,
41 pub(crate) ptr: std::ptr::NonNull<T>,
43 pub(crate) length: usize,
45 pub(crate) capacity: usize,
47 pub(crate) alignment: Alignment,
49 pub(crate) _marker: std::marker::PhantomData<T>,
51}
52
53unsafe impl<T: Send> Send for BufferMut<T> {}
55unsafe impl<T: Sync> Sync for BufferMut<T> {}
57
58impl<T> BufferMut<T> {
59 pub fn with_capacity(capacity: usize) -> Self {
61 Self::with_capacity_in(capacity, BufferAllocatorRef::statically_allocated())
62 }
63
64 pub fn with_capacity_in(capacity: usize, allocator: BufferAllocatorRef) -> Self {
66 Self::with_capacity_aligned_in(capacity, Alignment::of::<T>(), allocator)
67 }
68
69 pub fn with_capacity_aligned(capacity: usize, alignment: Alignment) -> Self {
76 Self::with_capacity_aligned_in(
77 capacity,
78 alignment,
79 BufferAllocatorRef::statically_allocated(),
80 )
81 }
82
83 pub fn with_capacity_aligned_in(
85 capacity: usize,
86 alignment: Alignment,
87 allocator: BufferAllocatorRef,
88 ) -> Self {
89 Self::with_capacity_preferred_aligned_in(
90 capacity,
91 alignment,
92 Some(Alignment::DEFAULT_ALIGNMENT),
93 allocator,
94 )
95 }
96
97 pub fn with_capacity_preferred_aligned(
102 capacity: usize,
103 alignment: Alignment,
104 preferred_alignment: Option<Alignment>,
105 ) -> Self {
106 Self::with_capacity_preferred_aligned_in(
107 capacity,
108 alignment,
109 preferred_alignment,
110 BufferAllocatorRef::statically_allocated(),
111 )
112 }
113
114 pub fn with_capacity_preferred_aligned_in(
116 capacity: usize,
117 alignment: Alignment,
118 preferred_alignment: Option<Alignment>,
119 allocator: BufferAllocatorRef,
120 ) -> Self {
121 const { assert!(size_of::<T>() != 0, "ZSTs are not supported") };
122 let actual = max(
123 alignment,
124 preferred_alignment.unwrap_or(Alignment::of::<u8>()),
125 );
126
127 if !alignment.is_aligned_to(Alignment::of::<T>()) {
128 misaligned_scalar_type(alignment, Alignment::of::<T>());
129 }
130
131 let size = capacity
132 .checked_mul(size_of::<T>())
133 .vortex_expect("buffer capacity overflow");
134 let layout = if size == 0 {
135 Layout::from_size_align(0, actual.as_usize())
136 .unwrap_or_else(|_| vortex_panic!("invalid empty buffer alignment"))
137 } else {
138 let allocation_size = size
139 .checked_add(actual.as_usize())
140 .vortex_expect("buffer capacity overflow");
141 Layout::from_size_align(allocation_size, 1).unwrap_or_else(|_| {
142 vortex_panic!("buffer capacity exceeds maximum allocation size")
143 })
144 };
145 let allocation = Allocation::allocate(layout, allocator);
146 let offset = allocation.ptr().as_ptr().align_offset(actual.as_usize());
147 let ptr = unsafe { allocation.ptr().add(offset).cast() };
149 let capacity = (allocation.size() - offset) / size_of::<T>();
150 Self {
151 allocation,
152 ptr,
153 length: 0,
154 capacity,
155 alignment,
156 _marker: Default::default(),
157 }
158 }
159
160 pub fn zeroed(len: usize) -> Self {
162 Self::zeroed_in(len, BufferAllocatorRef::statically_allocated())
163 }
164
165 pub fn zeroed_in(len: usize, allocator: BufferAllocatorRef) -> Self {
167 Self::zeroed_aligned_in(len, Alignment::of::<T>(), allocator)
168 }
169
170 pub fn zeroed_aligned(len: usize, alignment: Alignment) -> Self {
177 Self::zeroed_aligned_in(len, alignment, BufferAllocatorRef::statically_allocated())
178 }
179
180 pub fn zeroed_aligned_in(
182 len: usize,
183 alignment: Alignment,
184 allocator: BufferAllocatorRef,
185 ) -> Self {
186 Self::zeroed_preferred_aligned_in(
187 len,
188 alignment,
189 Some(Alignment::DEFAULT_ALIGNMENT),
190 allocator,
191 )
192 }
193
194 pub fn zeroed_preferred_aligned(
199 len: usize,
200 alignment: Alignment,
201 preferred_alignment: Option<Alignment>,
202 ) -> Self {
203 Self::zeroed_preferred_aligned_in(
204 len,
205 alignment,
206 preferred_alignment,
207 BufferAllocatorRef::statically_allocated(),
208 )
209 }
210
211 pub fn zeroed_preferred_aligned_in(
213 len: usize,
214 alignment: Alignment,
215 preferred_alignment: Option<Alignment>,
216 allocator: BufferAllocatorRef,
217 ) -> Self {
218 const { assert!(size_of::<T>() != 0, "ZSTs are not supported") };
219 let preferred_alignment = preferred_alignment.unwrap_or(Alignment::of::<u8>());
220 let actual_alignment = max(preferred_alignment, alignment);
221 let size = len
222 .checked_mul(size_of::<T>())
223 .vortex_expect("buffer length overflow");
224 let layout = if size == 0 {
225 Layout::from_size_align(0, actual_alignment.as_usize())
226 .unwrap_or_else(|_| vortex_panic!("invalid empty buffer alignment"))
227 } else {
228 let allocation_size = size
229 .checked_add(actual_alignment.as_usize())
230 .vortex_expect("buffer length overflow");
231 Layout::from_size_align(allocation_size, 1)
232 .unwrap_or_else(|_| vortex_panic!("buffer length exceeds maximum allocation size"))
233 };
234 let allocation = Allocation::allocate_zeroed(layout, allocator);
235 let offset = allocation
236 .ptr()
237 .as_ptr()
238 .align_offset(actual_alignment.as_usize());
239 let ptr = unsafe { allocation.ptr().add(offset).cast() };
241 let capacity = (allocation.size() - offset) / size_of::<T>();
242 Self {
243 allocation,
244 ptr,
245 length: len,
246 capacity,
247 alignment,
248 _marker: Default::default(),
249 }
250 }
251
252 pub fn empty() -> Self {
254 Self::empty_aligned(Alignment::of::<T>())
255 }
256
257 pub fn empty_aligned(alignment: Alignment) -> Self {
264 Self::empty_aligned_in(alignment, BufferAllocatorRef::statically_allocated())
265 }
266
267 pub fn empty_aligned_in(alignment: Alignment, allocator: BufferAllocatorRef) -> Self {
269 Self::with_capacity_aligned_in(0, alignment, allocator)
270 }
271
272 pub fn empty_preferred_aligned(
277 alignment: Alignment,
278 preferred_alignment: Option<Alignment>,
279 ) -> Self {
280 BufferMut::with_capacity_preferred_aligned_in(
281 0,
282 alignment,
283 preferred_alignment,
284 BufferAllocatorRef::statically_allocated(),
285 )
286 }
287
288 pub fn full(item: T, len: usize) -> Self
290 where
291 T: Copy,
292 {
293 Self::full_in(item, len, BufferAllocatorRef::statically_allocated())
294 }
295
296 pub fn full_in(item: T, len: usize, allocator: BufferAllocatorRef) -> Self
298 where
299 T: Copy,
300 {
301 let mut buffer = BufferMut::<T>::with_capacity_in(len, allocator);
302 buffer.push_n(item, len);
303 buffer
304 }
305
306 pub fn copy_from(other: impl AsRef<[T]>) -> Self
308 where
309 T: Copy,
310 {
311 Self::copy_from_in(other, BufferAllocatorRef::statically_allocated())
312 }
313
314 pub fn copy_from_in(other: impl AsRef<[T]>, allocator: BufferAllocatorRef) -> Self
316 where
317 T: Copy,
318 {
319 Self::copy_from_aligned_in(other, Alignment::of::<T>(), allocator)
320 }
321
322 pub fn copy_from_aligned(other: impl AsRef<[T]>, alignment: Alignment) -> Self
333 where
334 T: Copy,
335 {
336 Self::copy_from_aligned_in(other, alignment, BufferAllocatorRef::statically_allocated())
337 }
338
339 pub fn copy_from_aligned_in(
341 other: impl AsRef<[T]>,
342 alignment: Alignment,
343 allocator: BufferAllocatorRef,
344 ) -> Self
345 where
346 T: Copy,
347 {
348 Self::copy_from_preferred_aligned_in(
349 other,
350 alignment,
351 Some(Alignment::DEFAULT_ALIGNMENT),
352 allocator,
353 )
354 }
355
356 pub fn copy_from_preferred_aligned(
365 other: impl AsRef<[T]>,
366 alignment: Alignment,
367 preferred_alignment: Option<Alignment>,
368 ) -> Self
369 where
370 T: Copy,
371 {
372 Self::copy_from_preferred_aligned_in(
373 other,
374 alignment,
375 preferred_alignment,
376 BufferAllocatorRef::statically_allocated(),
377 )
378 }
379
380 pub fn copy_from_preferred_aligned_in(
382 other: impl AsRef<[T]>,
383 alignment: Alignment,
384 preferred_alignment: Option<Alignment>,
385 allocator: BufferAllocatorRef,
386 ) -> Self
387 where
388 T: Copy,
389 {
390 if !alignment.is_aligned_to(Alignment::of::<T>()) {
391 vortex_panic!("Given alignment is not aligned to type T")
392 }
393 let other = other.as_ref();
394 let mut buffer = Self::with_capacity_preferred_aligned_in(
395 other.len(),
396 alignment,
397 preferred_alignment,
398 allocator,
399 );
400 buffer.extend_from_slice(other);
401 debug_assert_eq!(buffer.alignment(), alignment);
402 buffer
403 }
404
405 #[allow(clippy::inline_always)]
407 #[inline(always)]
408 pub fn alignment(&self) -> Alignment {
409 self.alignment
410 }
411
412 #[cfg(test)]
413 pub(crate) fn allocator(&self) -> &BufferAllocatorRef {
414 self.allocation.allocator()
415 }
416
417 pub fn take(&mut self) -> Self {
419 let replacement =
420 Self::empty_aligned_in(self.alignment, self.allocation.allocator().clone());
421 std::mem::replace(self, replacement)
422 }
423
424 #[allow(clippy::inline_always)]
426 #[inline(always)]
427 pub fn len(&self) -> usize {
428 self.length
429 }
430
431 #[allow(clippy::inline_always)]
433 #[inline(always)]
434 pub fn is_empty(&self) -> bool {
435 self.length == 0
436 }
437
438 #[inline]
440 pub fn capacity(&self) -> usize {
441 self.capacity
442 }
443
444 #[allow(clippy::inline_always)]
446 #[inline(always)]
447 pub fn as_ptr(&self) -> *const T {
448 self.ptr.as_ptr()
449 }
450
451 #[allow(clippy::inline_always)]
453 #[inline(always)]
454 pub fn as_mut_ptr(&mut self) -> *mut T {
455 self.ptr.as_ptr()
456 }
457
458 #[inline]
460 pub fn as_slice(&self) -> &[T] {
461 unsafe { std::slice::from_raw_parts(self.as_ptr(), self.length) }
463 }
464
465 #[inline]
467 pub fn as_mut_slice(&mut self) -> &mut [T] {
468 unsafe { std::slice::from_raw_parts_mut(self.as_mut_ptr(), self.length) }
470 }
471
472 #[inline]
474 pub fn clear(&mut self) {
475 self.length = 0;
476 }
477
478 #[inline]
486 pub fn truncate(&mut self, len: usize) {
487 if len <= self.len() {
488 unsafe { self.set_len(len) };
490 }
491 }
492
493 #[inline]
495 pub fn reserve(&mut self, additional: usize) {
496 if additional <= self.capacity() - self.length {
497 return;
499 }
500
501 self.reserve_allocate(additional);
503 }
504
505 fn reserve_allocate(&mut self, additional: usize) {
529 let required_capacity = self
530 .length
531 .checked_add(additional)
532 .vortex_expect("buffer capacity overflow");
533 let required_bytes = required_capacity
534 .checked_mul(size_of::<T>())
535 .vortex_expect("buffer capacity overflow");
536 let capacity_bytes = self
537 .capacity
538 .checked_mul(size_of::<T>())
539 .vortex_expect("buffer capacity overflow");
540 let new_capacity_bytes = required_bytes
541 .max(capacity_bytes.saturating_mul(2))
542 .max(Alignment::DEFAULT_ALIGNMENT.as_usize());
543
544 let data_alignment = self.alignment.as_usize();
546 let new_allocation_bytes = new_capacity_bytes
547 .checked_add(data_alignment)
548 .vortex_expect("buffer capacity overflow");
549 let allocation_alignment = if self.allocation.size() == 0 {
550 1
551 } else {
552 self.allocation.alignment()
553 };
554 let new_layout = Layout::from_size_align(new_allocation_bytes, allocation_alignment)
555 .unwrap_or_else(|_| vortex_panic!("buffer capacity exceeds maximum allocation size"));
556 let initialized_bytes = self.length * size_of::<T>();
557
558 let needs_new_allocation = self.allocation.allocator().is_statically_allocated()
562 || new_layout.size() < self.allocation.size();
563
564 let data_offset = if needs_new_allocation {
565 let new_allocation =
566 Allocation::allocate(new_layout, self.allocation.allocator().clone());
567 let new_data_offset = new_allocation.ptr().as_ptr().align_offset(data_alignment);
568
569 unsafe {
572 std::ptr::copy_nonoverlapping(
573 self.ptr.cast::<u8>().as_ptr(),
574 new_allocation.ptr().as_ptr().add(new_data_offset),
575 initialized_bytes,
576 );
577 }
578
579 self.allocation = new_allocation;
580
581 new_data_offset
582 } else {
583 let old_data_offset =
584 self.ptr.cast::<u8>().addr().get() - self.allocation.ptr().addr().get();
585 self.allocation.grow(new_layout);
586
587 let new_data_offset = self.allocation.ptr().as_ptr().align_offset(data_alignment);
588
589 if new_data_offset != old_data_offset {
590 unsafe {
593 std::ptr::copy(
594 self.allocation.ptr().as_ptr().add(old_data_offset),
595 self.allocation.ptr().as_ptr().add(new_data_offset),
596 initialized_bytes,
597 );
598 }
599 }
600
601 new_data_offset
602 };
603
604 self.ptr = unsafe { self.allocation.ptr().add(data_offset).cast() };
607 self.capacity = new_capacity_bytes / size_of::<T>();
608 }
609
610 #[inline]
646 pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
647 let dst = unsafe { self.as_mut_ptr().add(self.length) }.cast::<MaybeUninit<T>>();
649 unsafe { std::slice::from_raw_parts_mut(dst, self.capacity() - self.length) }
650 }
651
652 #[inline]
661 pub unsafe fn set_len(&mut self, len: usize) {
662 debug_assert!(len <= self.capacity());
663 self.length = len;
664 }
665
666 #[inline]
668 pub fn push(&mut self, value: T) {
669 self.reserve(1);
670 unsafe { self.push_unchecked(value) }
671 }
672
673 #[inline]
679 pub unsafe fn push_unchecked(&mut self, item: T) {
680 unsafe {
682 let dst = self.as_mut_ptr().add(self.length);
683 dst.write(item);
684 }
685 self.length += 1;
686 }
687
688 #[inline]
692 pub fn push_n(&mut self, item: T, n: usize)
693 where
694 T: Copy,
695 {
696 self.reserve(n);
697 unsafe { self.push_n_unchecked(item, n) }
698 }
699
700 #[inline]
706 pub unsafe fn push_n_unchecked(&mut self, item: T, n: usize)
707 where
708 T: Copy,
709 {
710 let mut dst = unsafe { self.as_mut_ptr().add(self.length) };
712 unsafe {
714 let end = dst.add(n);
715 while dst < end {
716 dst.write(item);
717 dst = dst.add(1);
718 }
719 }
720 self.length += n;
721 }
722
723 #[inline]
749 pub fn extend_from_slice(&mut self, slice: &[T])
750 where
751 T: Copy,
752 {
753 self.reserve(slice.len());
754 let dst = self
755 .spare_capacity_mut()
756 .get_mut(..slice.len())
757 .vortex_expect("reserve guarantees sufficient spare capacity");
758 dst.write_copy_of_slice(slice);
759 self.length += slice.len();
760 }
761
762 pub fn into_byte_buffer(self) -> ByteBufferMut {
764 let capacity = self
765 .capacity
766 .checked_mul(size_of::<T>())
767 .vortex_expect("buffer capacity overflow");
768 ByteBufferMut {
769 allocation: self.allocation,
770 ptr: self.ptr.cast(),
771 length: self.length * size_of::<T>(),
772 capacity,
773 alignment: self.alignment,
774 _marker: Default::default(),
775 }
776 }
777
778 pub fn freeze(self) -> Buffer<T> {
780 let offset = self.ptr.cast::<u8>().addr().get() - self.allocation.ptr().addr().get();
781 Buffer::from_allocation(self.allocation, offset, self.length, self.alignment)
782 }
783
784 pub fn aligned(self, alignment: Alignment) -> Self
790 where
791 T: Copy,
792 {
793 if self.as_ptr().align_offset(alignment.as_usize()) == 0 {
794 Self { alignment, ..self }
795 } else {
796 let capacity = self.capacity();
797 let allocator = self.allocation.allocator().clone();
798 let mut aligned = Self::with_capacity_aligned_in(capacity, alignment, allocator);
799 aligned.extend_from_slice(&self);
800 aligned.capacity = capacity;
801 aligned
802 }
803 }
804
805 pub unsafe fn transmute<U>(self) -> BufferMut<U> {
817 assert_eq!(size_of::<T>(), size_of::<U>(), "Buffer type size mismatch");
818 assert_eq!(
819 align_of::<T>(),
820 align_of::<U>(),
821 "Buffer type alignment mismatch"
822 );
823
824 BufferMut {
825 allocation: self.allocation,
826 ptr: self.ptr.cast(),
827 length: self.length,
828 capacity: self.capacity,
829 alignment: self.alignment,
830 _marker: std::marker::PhantomData,
831 }
832 }
833}
834
835impl<T: Copy> Clone for BufferMut<T> {
836 fn clone(&self) -> Self {
837 let mut buffer = BufferMut::<T>::with_capacity_aligned_in(
838 self.capacity(),
839 self.alignment,
840 self.allocation.allocator().clone(),
841 );
842 buffer.extend_from_slice(self.as_slice());
843 buffer
844 }
845}
846
847impl<T: PartialEq> PartialEq for BufferMut<T> {
848 fn eq(&self, other: &Self) -> bool {
849 self.as_slice() == other.as_slice()
850 }
851}
852
853impl<T: Eq> Eq for BufferMut<T> {}
854
855impl<T: Debug> Debug for BufferMut<T> {
856 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
857 f.debug_struct(&format!("BufferMut<{}>", type_name::<T>()))
858 .field("length", &self.length)
859 .field("alignment", &self.alignment)
860 .field("as_slice", &TruncatedDebug(self.as_slice()))
861 .finish()
862 }
863}
864
865impl<T> Default for BufferMut<T> {
866 fn default() -> Self {
867 Self::empty()
868 }
869}
870
871impl<T> Deref for BufferMut<T> {
872 type Target = [T];
873
874 #[inline]
875 fn deref(&self) -> &Self::Target {
876 self.as_slice()
877 }
878}
879
880impl<T> DerefMut for BufferMut<T> {
881 #[inline]
882 fn deref_mut(&mut self) -> &mut Self::Target {
883 self.as_mut_slice()
884 }
885}
886
887impl<T> AsRef<[T]> for BufferMut<T> {
888 #[inline]
889 fn as_ref(&self) -> &[T] {
890 self.as_slice()
891 }
892}
893
894impl<T> AsMut<[T]> for BufferMut<T> {
895 #[inline]
896 fn as_mut(&mut self) -> &mut [T] {
897 self.as_mut_slice()
898 }
899}
900
901impl<T> BufferMut<T> {
902 fn extend_iter(&mut self, mut iter: impl Iterator<Item = T>) {
907 let (lower_bound, _) = iter.size_hint();
910
911 self.reserve(lower_bound);
914
915 let unwritten = self.capacity() - self.len();
916
917 let begin: *const T = self.spare_capacity_mut().as_mut_ptr().cast();
919 let mut dst: *mut T = begin.cast_mut();
920
921 for _ in 0..unwritten {
923 let Some(item) = iter.next() else {
924 break;
926 };
927
928 unsafe { dst.write(item) };
931
932 unsafe { dst = dst.add(1) };
937 }
938
939 let items_written = unsafe { dst.offset_from_unsigned(begin) };
942 let length = self.len() + items_written;
943
944 unsafe { self.set_len(length) };
946
947 iter.for_each(|item| self.push(item));
950 }
951
952 pub fn extend_trusted<I: TrustedLen<Item = T>>(&mut self, iter: I) {
957 let (_, upper_bound) = iter.size_hint();
958 self.reserve(
959 upper_bound
960 .vortex_expect("`TrustedLen` iterator somehow didn't have valid upper bound"),
961 );
962
963 let begin: *const T = self.spare_capacity_mut().as_mut_ptr().cast();
964 let mut dst: *mut T = begin.cast_mut();
965
966 iter.for_each(|item| {
967 unsafe { dst.write(item) };
970
971 unsafe { dst = dst.add(1) };
976 });
977
978 let items_written = unsafe { dst.offset_from_unsigned(begin) };
981 let length = self.len() + items_written;
982
983 unsafe { self.set_len(length) };
985 }
986
987 pub fn from_trusted_len_iter<I>(iter: I) -> Self
991 where
992 I: TrustedLen<Item = T>,
993 {
994 let (_, upper_bound) = iter.size_hint();
995 let mut buffer = Self::with_capacity(
996 upper_bound
997 .vortex_expect("`TrustedLen` iterator somehow didn't have valid upper bound"),
998 );
999
1000 buffer.extend_trusted(iter);
1001 buffer
1002 }
1003
1004 pub fn try_extend_trusted<E, I>(&mut self, iter: I) -> Result<(), E>
1009 where
1010 I: TrustedLen<Item = Result<T, E>>,
1011 {
1012 iter.process_results(|values| self.extend_trusted(values))
1013 }
1014
1015 pub fn try_from_trusted_len_iter<E, I>(iter: I) -> Result<Self, E>
1018 where
1019 I: TrustedLen<Item = Result<T, E>>,
1020 {
1021 iter.process_results(|values| Self::from_trusted_len_iter(values))
1022 }
1023}
1024
1025impl<T> Extend<T> for BufferMut<T> {
1026 #[inline]
1027 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1028 self.extend_iter(iter.into_iter())
1029 }
1030}
1031
1032impl<'a, T> Extend<&'a T> for BufferMut<T>
1033where
1034 T: Copy + 'a,
1035{
1036 #[inline]
1037 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1038 self.extend_iter(iter.into_iter().copied())
1039 }
1040}
1041
1042impl<T> FromIterator<T> for BufferMut<T> {
1043 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
1044 let iter = iter.into_iter();
1045 let mut buffer = Self::with_capacity(iter.size_hint().0);
1046 buffer.extend(iter);
1047 buffer
1048 }
1049}
1050
1051#[cold]
1052#[inline(never)]
1053fn misaligned_scalar_type(alignment: Alignment, scalar_align: Alignment) -> ! {
1054 vortex_panic!("Alignment {alignment} must align to the scalar type's alignment {scalar_align}")
1055}
1056
1057#[cfg(test)]
1058mod tests {
1059 use std::cell::Cell;
1060
1061 use allocator_api2::alloc::Global;
1062
1063 use crate::Alignment;
1064 use crate::BufferAllocatorRef;
1065 use crate::BufferMut;
1066 use crate::buffer_mut;
1067
1068 #[derive(Copy, Debug, PartialEq)]
1069 struct CopyWithCloneCounter<'a> {
1070 value: u32,
1071 clones: &'a Cell<usize>,
1072 }
1073
1074 #[allow(clippy::non_canonical_clone_impl)]
1075 impl Clone for CopyWithCloneCounter<'_> {
1076 fn clone(&self) -> Self {
1077 self.clones.set(self.clones.get() + 1);
1078 *self
1079 }
1080 }
1081
1082 #[test]
1083 fn extend_from_slice_skips_clone() {
1084 let clones = Cell::new(0);
1085 let source = [CopyWithCloneCounter {
1086 value: 42,
1087 clones: &clones,
1088 }];
1089 let mut buffer = BufferMut::empty();
1090 buffer.extend_from_slice(&source);
1091 buffer.extend_from_slice(&source);
1092 buffer.extend_from_slice(&[]);
1093 assert_eq!(clones.get(), 0);
1094 assert_eq!(buffer.as_slice(), &[source[0], source[0]]);
1095 assert_eq!(buffer.clone().as_slice(), buffer.as_slice());
1096 assert_eq!(clones.get(), 0);
1097 }
1098
1099 #[test]
1100 fn capacity() {
1101 let mut n = 57;
1102 let mut buf = BufferMut::<i32>::with_capacity_aligned(n, Alignment::new(1024));
1103 assert!(buf.capacity() >= 57);
1104
1105 while n > 0 {
1106 buf.push(0);
1107 assert!(buf.capacity() >= n);
1108 n -= 1
1109 }
1110
1111 assert_eq!(buf.alignment(), Alignment::new(1024));
1112 }
1113
1114 #[test]
1115 fn take_preserves_alignment_and_allocator() {
1116 let alignment = Alignment::new(1024);
1117 let allocator = BufferAllocatorRef::new(Global);
1118 let mut buffer = BufferMut::with_capacity_aligned_in(4, alignment, allocator.clone());
1119 buffer.extend([1u32, 2, 3]);
1120
1121 let taken = buffer.take();
1122
1123 assert_eq!(taken.as_slice(), [1, 2, 3]);
1124 assert!(taken.allocator().ptr_eq(&allocator));
1125 assert!(buffer.is_empty());
1126 assert_eq!(buffer.alignment(), alignment);
1127 assert!(buffer.allocator().ptr_eq(&allocator));
1128 }
1129
1130 #[test]
1131 fn growth_preserves_alignment_and_values() {
1132 let alignment = Alignment::new(4096);
1133 let mut buffer = BufferMut::<u64>::with_capacity_aligned(1, alignment);
1134
1135 for value in 0..10_000 {
1136 buffer.push(value);
1137 assert!(alignment.is_offset_aligned(buffer.as_ptr().addr()));
1138 }
1139
1140 assert_eq!(buffer.as_slice(), (0..10_000).collect::<Vec<_>>());
1141 }
1142
1143 #[test]
1144 fn growth_seeds_and_doubles_logical_capacity() {
1145 let alignment = Alignment::new(64);
1146 let mut buffer = BufferMut::<u8>::empty_aligned(alignment);
1147
1148 buffer.push(0);
1149 let capacity = buffer.capacity();
1150 assert_eq!(capacity, Alignment::DEFAULT_ALIGNMENT.as_usize());
1151
1152 buffer.reserve(capacity);
1153 assert_eq!(buffer.capacity(), capacity * 2);
1154 }
1155
1156 #[test]
1157 fn static_growth_copies_live_data() {
1158 let mut buffer = BufferMut::<u32>::with_capacity(1);
1159 let capacity = buffer.capacity();
1160 buffer.extend(std::iter::repeat_n(7, capacity));
1161 let old_ptr = buffer.as_ptr();
1162
1163 buffer.push(u32::MAX);
1164
1165 assert_ne!(buffer.as_ptr(), old_ptr);
1166 assert_eq!(&buffer[..capacity], vec![7; capacity]);
1167 assert_eq!(buffer[capacity], u32::MAX);
1168 }
1169
1170 #[test]
1171 fn growth_of_sliced_buffer_preserves_allocator_and_values() {
1172 let allocator = BufferAllocatorRef::new(Global);
1173 let mut buffer = BufferMut::<u32>::with_capacity_preferred_aligned_in(
1174 1024,
1175 Alignment::of::<u32>(),
1176 None,
1177 allocator.clone(),
1178 );
1179 buffer.extend_from_slice(&[7; 1024]);
1180 let sliced_ptr = buffer.as_ptr().wrapping_add(1016);
1181 let sliced = buffer.freeze().slice(1016..);
1182 let mut buffer = sliced.try_into_mut().unwrap();
1183 assert_eq!(buffer.as_ptr(), sliced_ptr);
1184
1185 buffer.extend_from_slice(&[8; 16]);
1187
1188 assert!(buffer.allocator().ptr_eq(&allocator));
1189 assert_eq!(&buffer[..8], &[7; 8]);
1190 assert_eq!(&buffer[8..], &[8; 16]);
1191 }
1192
1193 #[test]
1194 fn raising_logical_alignment_preserves_capacity() {
1195 let buffer =
1196 BufferMut::<u8>::with_capacity_preferred_aligned(1, Alignment::of::<u8>(), None);
1197 let capacity = buffer.capacity();
1198
1199 let mut buffer = buffer.aligned(Alignment::new(2));
1200
1201 assert_eq!(buffer.capacity(), capacity);
1202 buffer.extend(0..100);
1203 assert!(Alignment::new(2).is_ptr_aligned(buffer.as_ptr()));
1204 assert_eq!(buffer.as_slice(), (0..100).collect::<Vec<_>>());
1205 }
1206
1207 #[test]
1208 fn from_iter() {
1209 let buf = BufferMut::from_iter([0, 10, 20, 30]);
1210 assert_eq!(buf.as_slice(), &[0, 10, 20, 30]);
1211 }
1212
1213 #[test]
1214 fn try_from_trusted_len_iter_ok() {
1215 let buf = BufferMut::<i32>::try_from_trusted_len_iter(
1216 [0, 10, 20, 30].iter().map(|&v| Ok::<_, ()>(v)),
1217 )
1218 .unwrap();
1219 assert_eq!(buf.as_slice(), &[0, 10, 20, 30]);
1220 }
1221
1222 #[test]
1223 fn try_from_trusted_len_iter_err() {
1224 let result: Result<BufferMut<i32>, &'static str> = BufferMut::try_from_trusted_len_iter(
1225 [0, 10, 20, 30]
1226 .iter()
1227 .map(|&v| if v == 20 { Err("bad") } else { Ok(v) }),
1228 );
1229 assert_eq!(result.err(), Some("bad"));
1230 }
1231
1232 #[test]
1233 fn try_extend_trusted_retains_values_before_error() {
1234 let mut buf = BufferMut::from_iter([0, 10]);
1235 let result = buf.try_extend_trusted([Ok(20), Err("bad"), Ok(30)].into_iter());
1236
1237 assert_eq!(result, Err("bad"));
1238 assert_eq!(buf.as_slice(), &[0, 10, 20]);
1239 }
1240
1241 #[test]
1242 fn extend() {
1243 let mut buf = BufferMut::empty();
1244 buf.extend([0i32, 10, 20, 30]);
1245 buf.extend([40, 50, 60]);
1246 assert_eq!(buf.as_slice(), &[0, 10, 20, 30, 40, 50, 60]);
1247 }
1248
1249 #[test]
1250 fn push() {
1251 let mut buf = BufferMut::empty();
1252 buf.push(1);
1253 buf.push(2);
1254 buf.push(3);
1255 assert_eq!(buf.as_slice(), &[1, 2, 3]);
1256 }
1257
1258 #[test]
1259 fn push_n() {
1260 let mut buf = BufferMut::empty();
1261 buf.push_n(0, 100);
1262 assert_eq!(buf.as_slice(), &[0; 100]);
1263 }
1264
1265 #[test]
1266 fn as_mut() {
1267 let mut buf = buffer_mut![0, 1, 2];
1268 buf[1] = 0;
1270 buf.as_mut()[2] = 0;
1272 assert_eq!(buf.as_slice(), &[0, 0, 0]);
1273 }
1274
1275 #[test]
1276 fn buffer_mut_zeroed() {
1277 const LEN: usize = 17;
1278
1279 let mut buf = BufferMut::<u32>::zeroed(LEN);
1280
1281 assert_eq!(
1282 buf.as_ptr().align_offset(Alignment::of::<u32>().as_usize()),
1283 0
1284 );
1285 assert_eq!(buf.as_slice(), &[0; LEN]);
1286
1287 buf[3] = 7;
1288 assert_eq!(buf.as_slice()[3], 7);
1289 }
1290
1291 #[test]
1292 fn buffer_mut_zeroed_aligned() {
1293 const LEN: usize = 17;
1294 let alignment = Alignment::new(64);
1295
1296 let mut buf = BufferMut::<u32>::zeroed_aligned(LEN, alignment);
1297
1298 assert_eq!(buf.as_ptr().align_offset(alignment.as_usize()), 0);
1299 assert_eq!(buf.as_slice(), &[0; LEN]);
1300
1301 buf[3] = 7;
1302 assert_eq!(buf.as_slice()[3], 7);
1303 }
1304}