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::BitBuffer;
20use crate::Buffer;
21use crate::BufferAllocatorRef;
22use crate::ByteBufferMut;
23use crate::debug::TruncatedDebug;
24use crate::trusted_len::TrustedLen;
25
26pub struct BufferMut<T> {
40 pub(crate) allocation: Allocation,
42 pub(crate) ptr: std::ptr::NonNull<T>,
44 pub(crate) length: usize,
46 pub(crate) capacity: usize,
48 pub(crate) alignment: Alignment,
50 pub(crate) _marker: std::marker::PhantomData<T>,
52}
53
54unsafe impl<T: Send> Send for BufferMut<T> {}
56unsafe impl<T: Sync> Sync for BufferMut<T> {}
58
59impl<T> BufferMut<T> {
60 pub fn with_capacity(capacity: usize) -> Self {
62 Self::with_capacity_in(capacity, BufferAllocatorRef::statically_allocated())
63 }
64
65 pub fn with_capacity_in(capacity: usize, allocator: BufferAllocatorRef) -> Self {
67 Self::with_capacity_aligned_in(capacity, Alignment::of::<T>(), allocator)
68 }
69
70 pub fn with_capacity_aligned(capacity: usize, alignment: Alignment) -> Self {
77 Self::with_capacity_aligned_in(
78 capacity,
79 alignment,
80 BufferAllocatorRef::statically_allocated(),
81 )
82 }
83
84 pub fn with_capacity_aligned_in(
86 capacity: usize,
87 alignment: Alignment,
88 allocator: BufferAllocatorRef,
89 ) -> Self {
90 Self::with_capacity_preferred_aligned_in(
91 capacity,
92 alignment,
93 Some(Alignment::DEFAULT_ALIGNMENT),
94 allocator,
95 )
96 }
97
98 pub fn with_capacity_preferred_aligned(
103 capacity: usize,
104 alignment: Alignment,
105 preferred_alignment: Option<Alignment>,
106 ) -> Self {
107 Self::with_capacity_preferred_aligned_in(
108 capacity,
109 alignment,
110 preferred_alignment,
111 BufferAllocatorRef::statically_allocated(),
112 )
113 }
114
115 pub fn with_capacity_preferred_aligned_in(
117 capacity: usize,
118 alignment: Alignment,
119 preferred_alignment: Option<Alignment>,
120 allocator: BufferAllocatorRef,
121 ) -> Self {
122 const { assert!(size_of::<T>() != 0, "ZSTs are not supported") };
123 let actual = max(
124 alignment,
125 preferred_alignment.unwrap_or(Alignment::of::<u8>()),
126 );
127
128 if !alignment.is_aligned_to(Alignment::of::<T>()) {
129 misaligned_scalar_type(alignment, Alignment::of::<T>());
130 }
131
132 let size = capacity
133 .checked_mul(size_of::<T>())
134 .vortex_expect("buffer capacity overflow");
135 let layout = if size == 0 {
136 Layout::from_size_align(0, actual.as_usize())
137 .unwrap_or_else(|_| vortex_panic!("invalid empty buffer alignment"))
138 } else {
139 let allocation_size = size
140 .checked_add(actual.as_usize())
141 .vortex_expect("buffer capacity overflow");
142 Layout::from_size_align(allocation_size, 1).unwrap_or_else(|_| {
143 vortex_panic!("buffer capacity exceeds maximum allocation size")
144 })
145 };
146 let allocation = Allocation::allocate(layout, allocator);
147 let offset = allocation.ptr().as_ptr().align_offset(actual.as_usize());
148 let ptr = unsafe { allocation.ptr().add(offset).cast() };
150 let capacity = (allocation.size() - offset) / size_of::<T>();
151 Self {
152 allocation,
153 ptr,
154 length: 0,
155 capacity,
156 alignment,
157 _marker: Default::default(),
158 }
159 }
160
161 pub fn zeroed(len: usize) -> Self {
163 Self::zeroed_in(len, BufferAllocatorRef::statically_allocated())
164 }
165
166 pub fn zeroed_in(len: usize, allocator: BufferAllocatorRef) -> Self {
168 Self::zeroed_aligned_in(len, Alignment::of::<T>(), allocator)
169 }
170
171 pub fn zeroed_aligned(len: usize, alignment: Alignment) -> Self {
178 Self::zeroed_aligned_in(len, alignment, BufferAllocatorRef::statically_allocated())
179 }
180
181 pub fn zeroed_aligned_in(
183 len: usize,
184 alignment: Alignment,
185 allocator: BufferAllocatorRef,
186 ) -> Self {
187 Self::zeroed_preferred_aligned_in(
188 len,
189 alignment,
190 Some(Alignment::DEFAULT_ALIGNMENT),
191 allocator,
192 )
193 }
194
195 pub fn zeroed_preferred_aligned(
200 len: usize,
201 alignment: Alignment,
202 preferred_alignment: Option<Alignment>,
203 ) -> Self {
204 Self::zeroed_preferred_aligned_in(
205 len,
206 alignment,
207 preferred_alignment,
208 BufferAllocatorRef::statically_allocated(),
209 )
210 }
211
212 pub fn zeroed_preferred_aligned_in(
214 len: usize,
215 alignment: Alignment,
216 preferred_alignment: Option<Alignment>,
217 allocator: BufferAllocatorRef,
218 ) -> Self {
219 const { assert!(size_of::<T>() != 0, "ZSTs are not supported") };
220 let preferred_alignment = preferred_alignment.unwrap_or(Alignment::of::<u8>());
221 let actual_alignment = max(preferred_alignment, alignment);
222 let size = len
223 .checked_mul(size_of::<T>())
224 .vortex_expect("buffer length overflow");
225 let layout = if size == 0 {
226 Layout::from_size_align(0, actual_alignment.as_usize())
227 .unwrap_or_else(|_| vortex_panic!("invalid empty buffer alignment"))
228 } else {
229 let allocation_size = size
230 .checked_add(actual_alignment.as_usize())
231 .vortex_expect("buffer length overflow");
232 Layout::from_size_align(allocation_size, 1)
233 .unwrap_or_else(|_| vortex_panic!("buffer length exceeds maximum allocation size"))
234 };
235 let allocation = Allocation::allocate_zeroed(layout, allocator);
236 let offset = allocation
237 .ptr()
238 .as_ptr()
239 .align_offset(actual_alignment.as_usize());
240 let ptr = unsafe { allocation.ptr().add(offset).cast() };
242 let capacity = (allocation.size() - offset) / size_of::<T>();
243 Self {
244 allocation,
245 ptr,
246 length: len,
247 capacity,
248 alignment,
249 _marker: Default::default(),
250 }
251 }
252
253 pub fn empty() -> Self {
255 Self::empty_aligned(Alignment::of::<T>())
256 }
257
258 pub fn empty_aligned(alignment: Alignment) -> Self {
265 Self::empty_aligned_in(alignment, BufferAllocatorRef::statically_allocated())
266 }
267
268 pub fn empty_aligned_in(alignment: Alignment, allocator: BufferAllocatorRef) -> Self {
270 Self::with_capacity_aligned_in(0, alignment, allocator)
271 }
272
273 pub fn empty_preferred_aligned(
278 alignment: Alignment,
279 preferred_alignment: Option<Alignment>,
280 ) -> Self {
281 BufferMut::with_capacity_preferred_aligned_in(
282 0,
283 alignment,
284 preferred_alignment,
285 BufferAllocatorRef::statically_allocated(),
286 )
287 }
288
289 pub fn full(item: T, len: usize) -> Self
291 where
292 T: Copy,
293 {
294 Self::full_in(item, len, BufferAllocatorRef::statically_allocated())
295 }
296
297 pub fn full_in(item: T, len: usize, allocator: BufferAllocatorRef) -> Self
299 where
300 T: Copy,
301 {
302 let mut buffer = BufferMut::<T>::with_capacity_in(len, allocator);
303 buffer.push_n(item, len);
304 buffer
305 }
306
307 pub fn copy_from(other: impl AsRef<[T]>) -> Self
309 where
310 T: Copy,
311 {
312 Self::copy_from_in(other, BufferAllocatorRef::statically_allocated())
313 }
314
315 pub fn copy_from_in(other: impl AsRef<[T]>, allocator: BufferAllocatorRef) -> Self
317 where
318 T: Copy,
319 {
320 Self::copy_from_aligned_in(other, Alignment::of::<T>(), allocator)
321 }
322
323 pub fn copy_from_aligned(other: impl AsRef<[T]>, alignment: Alignment) -> Self
334 where
335 T: Copy,
336 {
337 Self::copy_from_aligned_in(other, alignment, BufferAllocatorRef::statically_allocated())
338 }
339
340 pub fn copy_from_aligned_in(
342 other: impl AsRef<[T]>,
343 alignment: Alignment,
344 allocator: BufferAllocatorRef,
345 ) -> Self
346 where
347 T: Copy,
348 {
349 Self::copy_from_preferred_aligned_in(
350 other,
351 alignment,
352 Some(Alignment::DEFAULT_ALIGNMENT),
353 allocator,
354 )
355 }
356
357 pub fn copy_from_preferred_aligned(
366 other: impl AsRef<[T]>,
367 alignment: Alignment,
368 preferred_alignment: Option<Alignment>,
369 ) -> Self
370 where
371 T: Copy,
372 {
373 Self::copy_from_preferred_aligned_in(
374 other,
375 alignment,
376 preferred_alignment,
377 BufferAllocatorRef::statically_allocated(),
378 )
379 }
380
381 pub fn copy_from_preferred_aligned_in(
383 other: impl AsRef<[T]>,
384 alignment: Alignment,
385 preferred_alignment: Option<Alignment>,
386 allocator: BufferAllocatorRef,
387 ) -> Self
388 where
389 T: Copy,
390 {
391 if !alignment.is_aligned_to(Alignment::of::<T>()) {
392 vortex_panic!("Given alignment is not aligned to type T")
393 }
394 let other = other.as_ref();
395 let mut buffer = Self::with_capacity_preferred_aligned_in(
396 other.len(),
397 alignment,
398 preferred_alignment,
399 allocator,
400 );
401 buffer.extend_from_slice(other);
402 debug_assert_eq!(buffer.alignment(), alignment);
403 buffer
404 }
405
406 #[allow(clippy::inline_always)]
408 #[inline(always)]
409 pub fn alignment(&self) -> Alignment {
410 self.alignment
411 }
412
413 pub fn take(&mut self) -> Self {
415 let replacement =
416 Self::empty_aligned_in(self.alignment, self.allocation.allocator().clone());
417 std::mem::replace(self, replacement)
418 }
419
420 #[allow(clippy::inline_always)]
422 #[inline(always)]
423 pub fn len(&self) -> usize {
424 self.length
425 }
426
427 #[allow(clippy::inline_always)]
429 #[inline(always)]
430 pub fn is_empty(&self) -> bool {
431 self.length == 0
432 }
433
434 #[inline]
436 pub fn capacity(&self) -> usize {
437 self.capacity
438 }
439
440 #[allow(clippy::inline_always)]
442 #[inline(always)]
443 pub fn as_ptr(&self) -> *const T {
444 self.ptr.as_ptr()
445 }
446
447 #[allow(clippy::inline_always)]
449 #[inline(always)]
450 pub fn as_mut_ptr(&mut self) -> *mut T {
451 self.ptr.as_ptr()
452 }
453
454 #[inline]
456 pub fn as_slice(&self) -> &[T] {
457 unsafe { std::slice::from_raw_parts(self.as_ptr(), self.length) }
459 }
460
461 #[inline]
463 pub fn as_mut_slice(&mut self) -> &mut [T] {
464 unsafe { std::slice::from_raw_parts_mut(self.as_mut_ptr(), self.length) }
466 }
467
468 #[inline]
470 pub fn clear(&mut self) {
471 self.length = 0;
472 }
473
474 #[inline]
482 pub fn truncate(&mut self, len: usize) {
483 if len <= self.len() {
484 unsafe { self.set_len(len) };
486 }
487 }
488
489 pub fn shrink_to_fit(&mut self) {
510 if self.allocation.size() == 0 {
511 return;
512 }
513
514 let alignment = self.alignment.as_usize();
515 if self.length == 0 {
516 *self = Self::empty_aligned_in(self.alignment, self.allocation.allocator().clone());
517 return;
518 }
519
520 let data_bytes = self.length * size_of::<T>();
521 let padding = if self.allocation.alignment() >= alignment {
525 0
526 } else {
527 alignment - 1
528 };
529 let offset = self.ptr.cast::<u8>().addr().get() - self.allocation.ptr().addr().get();
530
531 let max_offset = alignment.max(Alignment::DEFAULT_ALIGNMENT.as_usize()) + padding;
535 if offset > max_offset {
536 let offset = self.reallocate_exact(data_bytes + padding, data_bytes);
537 self.set_data_offset(offset);
538 return;
539 }
540
541 let new_size = offset + data_bytes + padding;
543 if self.allocation.size() <= new_size {
544 return;
545 }
546
547 if !self.allocation.shrink(new_size) {
548 return;
549 }
550
551 let shift = self
553 .allocation
554 .ptr()
555 .as_ptr()
556 .wrapping_add(offset)
557 .align_offset(alignment);
558
559 if shift != 0 {
560 unsafe {
568 std::ptr::copy(
569 self.allocation.ptr().as_ptr().add(offset),
570 self.allocation.ptr().as_ptr().add(offset + shift),
571 data_bytes,
572 );
573 }
574 }
575
576 self.set_data_offset(offset + shift);
577 }
578
579 fn set_data_offset(&mut self, offset: usize) {
581 self.ptr = unsafe { self.allocation.ptr().add(offset).cast() };
584 self.capacity = (self.allocation.size() - offset) / size_of::<T>();
585 }
586
587 fn reallocate_exact(&mut self, size: usize, data_bytes: usize) -> usize {
590 let layout = Layout::from_size_align(size, self.allocation.alignment())
591 .unwrap_or_else(|_| vortex_panic!("buffer capacity exceeds maximum allocation size"));
592 let allocation = Allocation::allocate(layout, self.allocation.allocator().clone());
593
594 let offset = allocation
595 .ptr()
596 .as_ptr()
597 .align_offset(self.alignment.as_usize());
598
599 unsafe {
602 std::ptr::copy_nonoverlapping(
603 self.ptr.cast::<u8>().as_ptr(),
604 allocation.ptr().as_ptr().add(offset),
605 data_bytes,
606 );
607 }
608
609 self.allocation = allocation;
610 offset
611 }
612
613 #[inline]
615 pub fn reserve(&mut self, additional: usize) {
616 if additional <= self.capacity() - self.length {
617 return;
619 }
620
621 self.reserve_allocate(additional);
623 }
624
625 fn reserve_allocate(&mut self, additional: usize) {
649 let required_capacity = self
650 .length
651 .checked_add(additional)
652 .vortex_expect("buffer capacity overflow");
653 let required_bytes = required_capacity
654 .checked_mul(size_of::<T>())
655 .vortex_expect("buffer capacity overflow");
656 let capacity_bytes = self
657 .capacity
658 .checked_mul(size_of::<T>())
659 .vortex_expect("buffer capacity overflow");
660 let new_capacity_bytes = required_bytes
661 .max(capacity_bytes.saturating_mul(2))
662 .max(Alignment::DEFAULT_ALIGNMENT.as_usize());
663
664 let data_alignment = self.alignment.as_usize();
666 let new_allocation_bytes = new_capacity_bytes
667 .checked_add(data_alignment)
668 .vortex_expect("buffer capacity overflow");
669 let allocation_alignment = if self.allocation.size() == 0 {
670 1
671 } else {
672 self.allocation.alignment()
673 };
674 let new_layout = Layout::from_size_align(new_allocation_bytes, allocation_alignment)
675 .unwrap_or_else(|_| vortex_panic!("buffer capacity exceeds maximum allocation size"));
676 let initialized_bytes = self.length * size_of::<T>();
677
678 let needs_new_allocation = self.allocation.allocator().is_statically_allocated()
682 || new_layout.size() < self.allocation.size();
683
684 let data_offset = if needs_new_allocation {
685 let new_allocation =
686 Allocation::allocate(new_layout, self.allocation.allocator().clone());
687 let new_data_offset = new_allocation.ptr().as_ptr().align_offset(data_alignment);
688
689 unsafe {
692 std::ptr::copy_nonoverlapping(
693 self.ptr.cast::<u8>().as_ptr(),
694 new_allocation.ptr().as_ptr().add(new_data_offset),
695 initialized_bytes,
696 );
697 }
698
699 self.allocation = new_allocation;
700
701 new_data_offset
702 } else {
703 let old_data_offset =
704 self.ptr.cast::<u8>().addr().get() - self.allocation.ptr().addr().get();
705 self.allocation.grow(new_layout);
706
707 let new_data_offset = self.allocation.ptr().as_ptr().align_offset(data_alignment);
708
709 if new_data_offset != old_data_offset {
710 unsafe {
713 std::ptr::copy(
714 self.allocation.ptr().as_ptr().add(old_data_offset),
715 self.allocation.ptr().as_ptr().add(new_data_offset),
716 initialized_bytes,
717 );
718 }
719 }
720
721 new_data_offset
722 };
723
724 self.ptr = unsafe { self.allocation.ptr().add(data_offset).cast() };
727 self.capacity = new_capacity_bytes / size_of::<T>();
728 }
729
730 #[inline]
766 pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
767 let dst = unsafe { self.as_mut_ptr().add(self.length) }.cast::<MaybeUninit<T>>();
769 unsafe { std::slice::from_raw_parts_mut(dst, self.capacity() - self.length) }
770 }
771
772 #[inline]
781 pub unsafe fn set_len(&mut self, len: usize) {
782 debug_assert!(len <= self.capacity());
783 self.length = len;
784 }
785
786 #[inline]
788 pub fn push(&mut self, value: T) {
789 self.reserve(1);
790 unsafe { self.push_unchecked(value) }
791 }
792
793 #[inline]
799 pub unsafe fn push_unchecked(&mut self, item: T) {
800 unsafe {
802 let dst = self.as_mut_ptr().add(self.length);
803 dst.write(item);
804 }
805 self.length += 1;
806 }
807
808 #[inline]
812 pub fn push_n(&mut self, item: T, n: usize)
813 where
814 T: Copy,
815 {
816 self.reserve(n);
817 unsafe { self.push_n_unchecked(item, n) }
818 }
819
820 #[inline]
826 pub unsafe fn push_n_unchecked(&mut self, item: T, n: usize)
827 where
828 T: Copy,
829 {
830 let mut dst = unsafe { self.as_mut_ptr().add(self.length) };
832 unsafe {
834 let end = dst.add(n);
835 while dst < end {
836 dst.write(item);
837 dst = dst.add(1);
838 }
839 }
840 self.length += n;
841 }
842
843 #[inline]
869 pub fn extend_from_slice(&mut self, slice: &[T])
870 where
871 T: Copy,
872 {
873 self.reserve(slice.len());
874 let dst = self
875 .spare_capacity_mut()
876 .get_mut(..slice.len())
877 .vortex_expect("reserve guarantees sufficient spare capacity");
878 dst.write_copy_of_slice(slice);
879 self.length += slice.len();
880 }
881
882 #[inline]
902 pub fn fill_where<const USE_RUNS: bool>(&mut self, positions: &BitBuffer, value: T)
903 where
904 T: Copy,
905 {
906 assert_eq!(
907 positions.len(),
908 self.len(),
909 "fill_where requires one position bit per buffer element",
910 );
911
912 if USE_RUNS {
913 let values = self.as_mut_slice();
914 for (start, end) in positions.set_slices() {
915 values[start..end].fill(value);
916 }
917 } else {
918 for index in positions.set_indices() {
919 self[index] = value;
920 }
921 }
922 }
923
924 pub fn into_byte_buffer(self) -> ByteBufferMut {
926 let capacity = self
927 .capacity
928 .checked_mul(size_of::<T>())
929 .vortex_expect("buffer capacity overflow");
930 ByteBufferMut {
931 allocation: self.allocation,
932 ptr: self.ptr.cast(),
933 length: self.length * size_of::<T>(),
934 capacity,
935 alignment: self.alignment,
936 _marker: Default::default(),
937 }
938 }
939
940 pub fn freeze(self) -> Buffer<T> {
942 let offset = self.ptr.cast::<u8>().addr().get() - self.allocation.ptr().addr().get();
943 Buffer::from_allocation(self.allocation, offset, self.length, self.alignment)
944 }
945
946 pub fn aligned(self, alignment: Alignment) -> Self
952 where
953 T: Copy,
954 {
955 if self.as_ptr().align_offset(alignment.as_usize()) == 0 {
956 Self { alignment, ..self }
957 } else {
958 let capacity = self.capacity();
959 let allocator = self.allocation.allocator().clone();
960 let mut aligned = Self::with_capacity_aligned_in(capacity, alignment, allocator);
961 aligned.extend_from_slice(&self);
962 aligned.capacity = capacity;
963 aligned
964 }
965 }
966
967 pub unsafe fn transmute<U>(self) -> BufferMut<U> {
979 assert_eq!(size_of::<T>(), size_of::<U>(), "Buffer type size mismatch");
980 assert_eq!(
981 align_of::<T>(),
982 align_of::<U>(),
983 "Buffer type alignment mismatch"
984 );
985
986 BufferMut {
987 allocation: self.allocation,
988 ptr: self.ptr.cast(),
989 length: self.length,
990 capacity: self.capacity,
991 alignment: self.alignment,
992 _marker: std::marker::PhantomData,
993 }
994 }
995}
996
997impl<T: Copy> Clone for BufferMut<T> {
998 fn clone(&self) -> Self {
999 let mut buffer = BufferMut::<T>::with_capacity_aligned_in(
1000 self.capacity(),
1001 self.alignment,
1002 self.allocation.allocator().clone(),
1003 );
1004 buffer.extend_from_slice(self.as_slice());
1005 buffer
1006 }
1007}
1008
1009impl<T: PartialEq> PartialEq for BufferMut<T> {
1010 fn eq(&self, other: &Self) -> bool {
1011 self.as_slice() == other.as_slice()
1012 }
1013}
1014
1015impl<T: Eq> Eq for BufferMut<T> {}
1016
1017impl<T: Debug> Debug for BufferMut<T> {
1018 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1019 f.debug_struct(&format!("BufferMut<{}>", type_name::<T>()))
1020 .field("length", &self.length)
1021 .field("alignment", &self.alignment)
1022 .field("as_slice", &TruncatedDebug(self.as_slice()))
1023 .finish()
1024 }
1025}
1026
1027impl<T> Default for BufferMut<T> {
1028 fn default() -> Self {
1029 Self::empty()
1030 }
1031}
1032
1033impl<T> Deref for BufferMut<T> {
1034 type Target = [T];
1035
1036 #[inline]
1037 fn deref(&self) -> &Self::Target {
1038 self.as_slice()
1039 }
1040}
1041
1042impl<T> DerefMut for BufferMut<T> {
1043 #[inline]
1044 fn deref_mut(&mut self) -> &mut Self::Target {
1045 self.as_mut_slice()
1046 }
1047}
1048
1049impl<T> AsRef<[T]> for BufferMut<T> {
1050 #[inline]
1051 fn as_ref(&self) -> &[T] {
1052 self.as_slice()
1053 }
1054}
1055
1056impl<T> AsMut<[T]> for BufferMut<T> {
1057 #[inline]
1058 fn as_mut(&mut self) -> &mut [T] {
1059 self.as_mut_slice()
1060 }
1061}
1062
1063impl<T> BufferMut<T> {
1064 fn extend_iter(&mut self, mut iter: impl Iterator<Item = T>) {
1069 let (lower_bound, _) = iter.size_hint();
1072
1073 self.reserve(lower_bound);
1076
1077 let unwritten = self.capacity() - self.len();
1078
1079 let begin: *const T = self.spare_capacity_mut().as_mut_ptr().cast();
1081 let mut dst: *mut T = begin.cast_mut();
1082
1083 for _ in 0..unwritten {
1085 let Some(item) = iter.next() else {
1086 break;
1088 };
1089
1090 unsafe { dst.write(item) };
1093
1094 unsafe { dst = dst.add(1) };
1099 }
1100
1101 let items_written = unsafe { dst.offset_from_unsigned(begin) };
1104 let length = self.len() + items_written;
1105
1106 unsafe { self.set_len(length) };
1108
1109 iter.for_each(|item| self.push(item));
1112 }
1113
1114 pub fn extend_trusted<I: TrustedLen<Item = T>>(&mut self, iter: I) {
1119 let (_, upper_bound) = iter.size_hint();
1120 self.reserve(
1121 upper_bound
1122 .vortex_expect("`TrustedLen` iterator somehow didn't have valid upper bound"),
1123 );
1124
1125 let begin: *const T = self.spare_capacity_mut().as_mut_ptr().cast();
1126 let mut dst: *mut T = begin.cast_mut();
1127
1128 iter.for_each(|item| {
1129 unsafe { dst.write(item) };
1132
1133 unsafe { dst = dst.add(1) };
1138 });
1139
1140 let items_written = unsafe { dst.offset_from_unsigned(begin) };
1143 let length = self.len() + items_written;
1144
1145 unsafe { self.set_len(length) };
1147 }
1148
1149 pub fn from_trusted_len_iter<I>(iter: I) -> Self
1153 where
1154 I: TrustedLen<Item = T>,
1155 {
1156 let (_, upper_bound) = iter.size_hint();
1157 let mut buffer = Self::with_capacity(
1158 upper_bound
1159 .vortex_expect("`TrustedLen` iterator somehow didn't have valid upper bound"),
1160 );
1161
1162 buffer.extend_trusted(iter);
1163 buffer
1164 }
1165
1166 pub fn try_extend_trusted<E, I>(&mut self, iter: I) -> Result<(), E>
1171 where
1172 I: TrustedLen<Item = Result<T, E>>,
1173 {
1174 iter.process_results(|values| self.extend_trusted(values))
1175 }
1176
1177 pub fn try_from_trusted_len_iter<E, I>(iter: I) -> Result<Self, E>
1180 where
1181 I: TrustedLen<Item = Result<T, E>>,
1182 {
1183 iter.process_results(|values| Self::from_trusted_len_iter(values))
1184 }
1185}
1186
1187impl<T> Extend<T> for BufferMut<T> {
1188 #[inline]
1189 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1190 self.extend_iter(iter.into_iter())
1191 }
1192}
1193
1194impl<'a, T> Extend<&'a T> for BufferMut<T>
1195where
1196 T: Copy + 'a,
1197{
1198 #[inline]
1199 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1200 self.extend_iter(iter.into_iter().copied())
1201 }
1202}
1203
1204impl<T> FromIterator<T> for BufferMut<T> {
1205 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
1206 let iter = iter.into_iter();
1207 let mut buffer = Self::with_capacity(iter.size_hint().0);
1208 buffer.extend(iter);
1209 buffer
1210 }
1211}
1212
1213#[cold]
1214#[inline(never)]
1215fn misaligned_scalar_type(alignment: Alignment, scalar_align: Alignment) -> ! {
1216 vortex_panic!("Alignment {alignment} must align to the scalar type's alignment {scalar_align}")
1217}
1218
1219#[cfg(test)]
1220mod tests {
1221 use std::cell::Cell;
1222
1223 use allocator_api2::alloc::Global;
1224 use rstest::rstest;
1225
1226 use crate::Alignment;
1227 use crate::BitBuffer;
1228 use crate::BufferAllocatorRef;
1229 use crate::BufferMut;
1230 use crate::buffer_mut;
1231
1232 #[track_caller]
1233 fn assert_fill_where(values: &[u32], positions: &BitBuffer, expected: &[u32]) {
1234 let mut by_index = BufferMut::copy_from(values);
1235 by_index.fill_where::<false>(positions, 0);
1236 assert_eq!(by_index.as_slice(), expected);
1237
1238 let mut by_run = BufferMut::copy_from(values);
1239 by_run.fill_where::<true>(positions, 0);
1240 assert_eq!(by_run.as_slice(), expected);
1241 }
1242
1243 #[derive(Copy, Debug, PartialEq)]
1244 struct CopyWithCloneCounter<'a> {
1245 value: u32,
1246 clones: &'a Cell<usize>,
1247 }
1248
1249 #[allow(clippy::non_canonical_clone_impl)]
1250 impl Clone for CopyWithCloneCounter<'_> {
1251 fn clone(&self) -> Self {
1252 self.clones.set(self.clones.get() + 1);
1253 *self
1254 }
1255 }
1256
1257 #[test]
1258 fn extend_from_slice_skips_clone() {
1259 let clones = Cell::new(0);
1260 let source = [CopyWithCloneCounter {
1261 value: 42,
1262 clones: &clones,
1263 }];
1264 let mut buffer = BufferMut::empty();
1265 buffer.extend_from_slice(&source);
1266 buffer.extend_from_slice(&source);
1267 buffer.extend_from_slice(&[]);
1268 assert_eq!(clones.get(), 0);
1269 assert_eq!(buffer.as_slice(), &[source[0], source[0]]);
1270 assert_eq!(buffer.clone().as_slice(), buffer.as_slice());
1271 assert_eq!(clones.get(), 0);
1272 }
1273
1274 #[test]
1275 fn capacity() {
1276 let mut n = 57;
1277 let mut buf = BufferMut::<i32>::with_capacity_aligned(n, Alignment::new(1024));
1278 assert!(buf.capacity() >= 57);
1279
1280 while n > 0 {
1281 buf.push(0);
1282 assert!(buf.capacity() >= n);
1283 n -= 1
1284 }
1285
1286 assert_eq!(buf.alignment(), Alignment::new(1024));
1287 }
1288
1289 #[test]
1290 fn take_preserves_alignment_and_allocator() {
1291 let alignment = Alignment::new(1024);
1292 let allocator = BufferAllocatorRef::new(Global);
1293 let mut buffer = BufferMut::with_capacity_aligned_in(4, alignment, allocator.clone());
1294 buffer.extend([1u32, 2, 3]);
1295
1296 let taken = buffer.take();
1297
1298 assert_eq!(taken.as_slice(), [1, 2, 3]);
1299 assert!(taken.allocation.allocator().ptr_eq(&allocator));
1300 assert!(buffer.is_empty());
1301 assert_eq!(buffer.alignment(), alignment);
1302 assert!(buffer.allocation.allocator().ptr_eq(&allocator));
1303 }
1304
1305 #[test]
1306 fn growth_preserves_alignment_and_values() {
1307 let alignment = Alignment::new(4096);
1308 let mut buffer = BufferMut::<u64>::with_capacity_aligned(1, alignment);
1309
1310 for value in 0..10_000 {
1311 buffer.push(value);
1312 assert!(alignment.is_offset_aligned(buffer.as_ptr().addr()));
1313 }
1314
1315 assert_eq!(buffer.as_slice(), (0..10_000).collect::<Vec<_>>());
1316 }
1317
1318 #[test]
1319 fn growth_seeds_and_doubles_logical_capacity() {
1320 let alignment = Alignment::new(64);
1321 let mut buffer = BufferMut::<u8>::empty_aligned(alignment);
1322
1323 buffer.push(0);
1324 let capacity = buffer.capacity();
1325 assert_eq!(capacity, Alignment::DEFAULT_ALIGNMENT.as_usize());
1326
1327 buffer.reserve(capacity);
1328 assert_eq!(buffer.capacity(), capacity * 2);
1329 }
1330
1331 #[test]
1332 fn static_growth_copies_live_data() {
1333 let mut buffer = BufferMut::<u32>::with_capacity(1);
1334 let capacity = buffer.capacity();
1335 buffer.extend(std::iter::repeat_n(7, capacity));
1336 let old_ptr = buffer.as_ptr();
1337
1338 buffer.push(u32::MAX);
1339
1340 assert_ne!(buffer.as_ptr(), old_ptr);
1341 assert_eq!(&buffer[..capacity], vec![7; capacity]);
1342 assert_eq!(buffer[capacity], u32::MAX);
1343 }
1344
1345 #[test]
1346 fn growth_of_sliced_buffer_preserves_allocator_and_values() {
1347 let allocator = BufferAllocatorRef::new(Global);
1348 let mut buffer = BufferMut::<u32>::with_capacity_preferred_aligned_in(
1349 1024,
1350 Alignment::of::<u32>(),
1351 None,
1352 allocator.clone(),
1353 );
1354 buffer.extend_from_slice(&[7; 1024]);
1355 let sliced_ptr = buffer.as_ptr().wrapping_add(1016);
1356 let sliced = buffer.freeze().slice(1016..);
1357 let mut buffer = sliced.try_into_mut().unwrap();
1358 assert_eq!(buffer.as_ptr(), sliced_ptr);
1359
1360 buffer.extend_from_slice(&[8; 16]);
1362
1363 assert!(buffer.allocation.allocator().ptr_eq(&allocator));
1364 assert_eq!(&buffer[..8], &[7; 8]);
1365 assert_eq!(&buffer[8..], &[8; 16]);
1366 }
1367
1368 #[test]
1369 fn raising_logical_alignment_preserves_capacity() {
1370 let buffer =
1371 BufferMut::<u8>::with_capacity_preferred_aligned(1, Alignment::of::<u8>(), None);
1372 let capacity = buffer.capacity();
1373
1374 let mut buffer = buffer.aligned(Alignment::new(2));
1375
1376 assert_eq!(buffer.capacity(), capacity);
1377 buffer.extend(0..100);
1378 assert!(Alignment::new(2).is_ptr_aligned(buffer.as_ptr()));
1379 assert_eq!(buffer.as_slice(), (0..100).collect::<Vec<_>>());
1380 }
1381
1382 #[test]
1383 fn from_iter() {
1384 let buf = BufferMut::from_iter([0, 10, 20, 30]);
1385 assert_eq!(buf.as_slice(), &[0, 10, 20, 30]);
1386 }
1387
1388 #[test]
1389 fn try_from_trusted_len_iter_ok() {
1390 let buf = BufferMut::<i32>::try_from_trusted_len_iter(
1391 [0, 10, 20, 30].iter().map(|&v| Ok::<_, ()>(v)),
1392 )
1393 .unwrap();
1394 assert_eq!(buf.as_slice(), &[0, 10, 20, 30]);
1395 }
1396
1397 #[test]
1398 fn try_from_trusted_len_iter_err() {
1399 let result: Result<BufferMut<i32>, &'static str> = BufferMut::try_from_trusted_len_iter(
1400 [0, 10, 20, 30]
1401 .iter()
1402 .map(|&v| if v == 20 { Err("bad") } else { Ok(v) }),
1403 );
1404 assert_eq!(result.err(), Some("bad"));
1405 }
1406
1407 #[test]
1408 fn try_extend_trusted_retains_values_before_error() {
1409 let mut buf = BufferMut::from_iter([0, 10]);
1410 let result = buf.try_extend_trusted([Ok(20), Err("bad"), Ok(30)].into_iter());
1411
1412 assert_eq!(result, Err("bad"));
1413 assert_eq!(buf.as_slice(), &[0, 10, 20]);
1414 }
1415
1416 #[test]
1417 fn extend() {
1418 let mut buf = BufferMut::empty();
1419 buf.extend([0i32, 10, 20, 30]);
1420 buf.extend([40, 50, 60]);
1421 assert_eq!(buf.as_slice(), &[0, 10, 20, 30, 40, 50, 60]);
1422 }
1423
1424 #[test]
1425 fn push() {
1426 let mut buf = BufferMut::empty();
1427 buf.push(1);
1428 buf.push(2);
1429 buf.push(3);
1430 assert_eq!(buf.as_slice(), &[1, 2, 3]);
1431 }
1432
1433 #[test]
1434 fn push_n() {
1435 let mut buf = BufferMut::empty();
1436 buf.push_n(0, 100);
1437 assert_eq!(buf.as_slice(), &[0; 100]);
1438 }
1439
1440 #[test]
1441 fn as_mut() {
1442 let mut buf = buffer_mut![0, 1, 2];
1443 buf[1] = 0;
1445 buf.as_mut()[2] = 0;
1447 assert_eq!(buf.as_slice(), &[0, 0, 0]);
1448 }
1449
1450 #[test]
1451 fn buffer_mut_zeroed() {
1452 const LEN: usize = 17;
1453
1454 let mut buf = BufferMut::<u32>::zeroed(LEN);
1455
1456 assert_eq!(
1457 buf.as_ptr().align_offset(Alignment::of::<u32>().as_usize()),
1458 0
1459 );
1460 assert_eq!(buf.as_slice(), &[0; LEN]);
1461
1462 buf[3] = 7;
1463 assert_eq!(buf.as_slice()[3], 7);
1464 }
1465
1466 #[test]
1467 fn buffer_mut_zeroed_aligned() {
1468 const LEN: usize = 17;
1469 let alignment = Alignment::new(64);
1470
1471 let mut buf = BufferMut::<u32>::zeroed_aligned(LEN, alignment);
1472
1473 assert_eq!(buf.as_ptr().align_offset(alignment.as_usize()), 0);
1474 assert_eq!(buf.as_slice(), &[0; LEN]);
1475
1476 buf[3] = 7;
1477 assert_eq!(buf.as_slice()[3], 7);
1478 }
1479
1480 #[rstest]
1481 #[case::no_position([false, false, false, false], [1, 2, 3, 4])]
1482 #[case::some_positions([true, false, false, true], [0, 2, 3, 0])]
1483 #[case::every_position([true, true, true, true], [0, 0, 0, 0])]
1484 fn fill_where_overwrites_only_set_positions(
1485 #[case] positions: [bool; 4],
1486 #[case] expected: [u32; 4],
1487 ) {
1488 assert_fill_where(&[1, 2, 3, 4], &BitBuffer::from_iter(positions), &expected);
1489 }
1490
1491 #[test]
1492 fn fill_where_reads_positions_from_their_offset() {
1493 let positions = BitBuffer::from_iter([false, true, false, false, true]).slice(1..);
1494 assert_fill_where(&[1, 2, 3, 4], &positions, &[0, 2, 3, 0]);
1495 }
1496
1497 #[test]
1498 fn fill_where_accepts_an_empty_buffer() {
1499 assert_fill_where(&[], &BitBuffer::empty(), &[]);
1500 }
1501
1502 #[test]
1503 #[should_panic(expected = "fill_where requires one position bit per buffer element")]
1504 fn fill_where_rejects_positions_of_another_length() {
1505 let mut buffer = BufferMut::from_iter([1u32, 2, 3]);
1506 buffer.fill_where::<false>(&BitBuffer::from_iter([true, false]), 0);
1507 }
1508}