1use std::alloc::Layout;
7use std::any::Any;
8use std::fmt;
9use std::fmt::Debug;
10use std::mem::ManuallyDrop;
11use std::ptr::NonNull;
12use std::sync::Arc;
13
14use allocator_api2::alloc::AllocError;
15use allocator_api2::alloc::Allocator;
16use allocator_api2::alloc::Global;
17use allocator_api2::alloc::handle_alloc_error;
18use vortex_error::VortexExpect;
19
20use crate::Alignment;
21use crate::BufferMut;
22
23pub trait BufferAllocator: Allocator + Debug + Send + Sync + 'static {}
27
28impl<A> BufferAllocator for A where A: Allocator + Debug + Send + Sync + 'static {}
29
30#[derive(Clone)]
35pub struct BufferAllocatorRef(
36 Option<Arc<dyn BufferAllocator>>,
39);
40
41impl BufferAllocatorRef {
42 pub fn new(allocator: impl BufferAllocator) -> Self {
44 Self(Some(Arc::new(allocator)))
45 }
46
47 pub fn statically_allocated() -> Self {
49 Self(None)
50 }
51
52 pub fn static_ref() -> &'static Self {
54 &STATIC_ALLOCATOR
55 }
56
57 pub(crate) fn is_statically_allocated(&self) -> bool {
58 self.0.is_none()
59 }
60
61 pub fn ptr_eq(&self, other: &Self) -> bool {
63 match (&self.0, &other.0) {
64 (None, None) => true,
65 (Some(lhs), Some(rhs)) => Arc::ptr_eq(lhs, rhs),
66 _ => false,
67 }
68 }
69
70 pub fn with_capacity<T>(&self, capacity: usize) -> BufferMut<T> {
72 BufferMut::with_capacity_in(capacity, self.clone())
73 }
74
75 pub fn with_capacity_aligned<T>(&self, capacity: usize, alignment: Alignment) -> BufferMut<T> {
77 BufferMut::with_capacity_aligned_in(capacity, alignment, self.clone())
78 }
79
80 pub fn zeroed<T>(&self, len: usize) -> BufferMut<T> {
82 BufferMut::zeroed_in(len, self.clone())
83 }
84
85 pub fn copy_from<T: Copy>(&self, values: impl AsRef<[T]>) -> BufferMut<T> {
87 BufferMut::copy_from_in(values, self.clone())
88 }
89}
90
91impl Debug for BufferAllocatorRef {
92 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93 match &self.0 {
94 Some(allocator) => allocator.fmt(f),
95 None => StaticBufferAllocator.fmt(f),
96 }
97 }
98}
99
100unsafe impl Allocator for BufferAllocatorRef {
102 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
103 match &self.0 {
104 Some(allocator) => allocator.allocate(layout),
105 None => Global.allocate(layout),
106 }
107 }
108
109 fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
110 match &self.0 {
111 Some(allocator) => allocator.allocate_zeroed(layout),
112 None => Global.allocate_zeroed(layout),
113 }
114 }
115
116 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
117 match &self.0 {
119 Some(allocator) => unsafe { allocator.deallocate(ptr, layout) },
120 None => unsafe { Global.deallocate(ptr, layout) },
121 }
122 }
123
124 unsafe fn grow(
125 &self,
126 ptr: NonNull<u8>,
127 old_layout: Layout,
128 new_layout: Layout,
129 ) -> Result<NonNull<[u8]>, AllocError> {
130 match &self.0 {
132 Some(allocator) => unsafe { allocator.grow(ptr, old_layout, new_layout) },
133 None => unsafe { Global.grow(ptr, old_layout, new_layout) },
134 }
135 }
136
137 unsafe fn grow_zeroed(
138 &self,
139 ptr: NonNull<u8>,
140 old_layout: Layout,
141 new_layout: Layout,
142 ) -> Result<NonNull<[u8]>, AllocError> {
143 match &self.0 {
145 Some(allocator) => unsafe { allocator.grow_zeroed(ptr, old_layout, new_layout) },
146 None => unsafe { Global.grow_zeroed(ptr, old_layout, new_layout) },
147 }
148 }
149
150 unsafe fn shrink(
151 &self,
152 ptr: NonNull<u8>,
153 old_layout: Layout,
154 new_layout: Layout,
155 ) -> Result<NonNull<[u8]>, AllocError> {
156 match &self.0 {
158 Some(allocator) => unsafe { allocator.shrink(ptr, old_layout, new_layout) },
159 None => unsafe { Global.shrink(ptr, old_layout, new_layout) },
160 }
161 }
162}
163
164#[derive(Clone, Copy, Debug, Default)]
166pub struct StaticBufferAllocator;
167
168impl StaticBufferAllocator {
169 pub fn with_capacity<T>(capacity: usize) -> BufferMut<T> {
171 BufferMut::with_capacity(capacity)
172 }
173
174 pub fn with_capacity_aligned<T>(capacity: usize, alignment: Alignment) -> BufferMut<T> {
176 BufferMut::with_capacity_aligned(capacity, alignment)
177 }
178
179 pub fn zeroed<T>(len: usize) -> BufferMut<T> {
181 BufferMut::zeroed(len)
182 }
183
184 pub fn copy_from<T: Copy>(values: impl AsRef<[T]>) -> BufferMut<T> {
186 BufferMut::copy_from(values)
187 }
188}
189
190unsafe impl Allocator for StaticBufferAllocator {
192 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
193 Global.allocate(layout)
194 }
195
196 fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
197 Global.allocate_zeroed(layout)
198 }
199
200 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
201 unsafe { Global.deallocate(ptr, layout) }
203 }
204
205 unsafe fn grow(
206 &self,
207 ptr: NonNull<u8>,
208 old_layout: Layout,
209 new_layout: Layout,
210 ) -> Result<NonNull<[u8]>, AllocError> {
211 unsafe { Global.grow(ptr, old_layout, new_layout) }
213 }
214
215 unsafe fn grow_zeroed(
216 &self,
217 ptr: NonNull<u8>,
218 old_layout: Layout,
219 new_layout: Layout,
220 ) -> Result<NonNull<[u8]>, AllocError> {
221 unsafe { Global.grow_zeroed(ptr, old_layout, new_layout) }
223 }
224
225 unsafe fn shrink(
226 &self,
227 ptr: NonNull<u8>,
228 old_layout: Layout,
229 new_layout: Layout,
230 ) -> Result<NonNull<[u8]>, AllocError> {
231 unsafe { Global.shrink(ptr, old_layout, new_layout) }
233 }
234}
235
236static STATIC_ALLOCATOR: BufferAllocatorRef = BufferAllocatorRef(None);
237
238pub(crate) struct Allocation {
239 ptr: NonNull<u8>,
240 layout: Layout,
241 allocator: BufferAllocatorRef,
242}
243
244unsafe impl Send for Allocation {}
246unsafe impl Sync for Allocation {}
248
249impl Allocation {
250 pub(crate) fn allocate(layout: Layout, allocator: BufferAllocatorRef) -> Self {
251 Self::allocate_impl(layout, allocator, false)
252 }
253
254 pub(crate) fn allocate_zeroed(layout: Layout, allocator: BufferAllocatorRef) -> Self {
255 Self::allocate_impl(layout, allocator, true)
256 }
257
258 pub(crate) fn from_vec<T>(vec: Vec<T>) -> Self {
259 assert!(!std::mem::needs_drop::<T>());
260
261 let mut vec = ManuallyDrop::new(vec);
262 let layout = Layout::array::<T>(vec.capacity())
263 .unwrap_or_else(|_| unreachable!("a Vec capacity always has a valid layout"));
264 let ptr = NonNull::new(vec.as_mut_ptr().cast())
265 .vortex_expect("a Vec always has a non-null pointer");
266
267 Self {
268 ptr,
269 layout,
270 allocator: BufferAllocatorRef::statically_allocated(),
271 }
272 }
273
274 fn allocate_impl(layout: Layout, allocator: BufferAllocatorRef, zeroed: bool) -> Self {
275 if layout.size() == 0 {
276 return Self {
277 ptr: layout.dangling_ptr(),
278 layout,
279 allocator,
280 };
281 }
282
283 let allocation = if zeroed {
284 allocator.allocate_zeroed(layout)
285 } else {
286 allocator.allocate(layout)
287 }
288 .unwrap_or_else(|_| handle_alloc_error(layout));
289
290 Self {
291 ptr: allocation.cast(),
292 layout,
293 allocator,
294 }
295 }
296
297 #[allow(clippy::inline_always)]
298 #[inline(always)]
299 pub(crate) fn ptr(&self) -> NonNull<u8> {
300 self.ptr
301 }
302
303 #[allow(clippy::inline_always)]
304 #[inline(always)]
305 pub(crate) fn size(&self) -> usize {
306 self.layout.size()
307 }
308
309 #[allow(clippy::inline_always)]
310 #[inline(always)]
311 pub(crate) fn alignment(&self) -> usize {
312 self.layout.align()
313 }
314
315 #[allow(clippy::inline_always)]
316 #[inline(always)]
317 pub(crate) fn allocator(&self) -> &BufferAllocatorRef {
318 &self.allocator
319 }
320
321 pub(crate) fn grow(&mut self, new_layout: Layout) {
322 let allocation = if self.layout.size() == 0 {
323 self.allocator.allocate(new_layout)
324 } else {
325 unsafe { self.allocator.grow(self.ptr, self.layout, new_layout) }
328 }
329 .unwrap_or_else(|_| handle_alloc_error(new_layout));
330 self.ptr = allocation.cast();
331 self.layout = new_layout;
332 }
333
334 pub(crate) fn shrink(&mut self, new_size: usize) -> bool {
339 debug_assert!(new_size > 0 && new_size <= self.layout.size());
340
341 let Ok(new_layout) = Layout::from_size_align(new_size, self.layout.align()) else {
342 return false;
343 };
344
345 match unsafe { self.allocator.shrink(self.ptr, self.layout, new_layout) } {
348 Ok(allocation) => {
349 self.ptr = allocation.cast();
350 self.layout = new_layout;
351 true
352 }
353 Err(_) => false,
354 }
355 }
356}
357
358impl Drop for Allocation {
359 fn drop(&mut self) {
360 if self.layout.size() == 0 {
361 return;
362 }
363 unsafe { self.allocator.deallocate(self.ptr, self.layout) }
365 }
366}
367
368pub(crate) enum BufferBacking {
369 Owned(Allocation),
370 Bytes(bytes::Bytes),
371 #[cfg(feature = "arrow")]
372 Arrow(arrow_buffer::Buffer),
373 External {
374 _owner: Box<dyn Any + Send + Sync>,
375 },
376}
377
378impl BufferBacking {
379 #[allow(clippy::inline_always)]
380 #[inline(always)]
381 pub(crate) fn allocator(&self) -> &BufferAllocatorRef {
382 match self {
383 Self::Owned(allocation) => allocation.allocator(),
384 Self::Bytes(_) | Self::External { .. } => &STATIC_ALLOCATOR,
385 #[cfg(feature = "arrow")]
386 Self::Arrow(_) => &STATIC_ALLOCATOR,
387 }
388 }
389}
390
391#[cfg(test)]
392mod tests {
393 use std::alloc::Layout;
394 use std::ptr::NonNull;
395 use std::sync::Arc;
396 use std::sync::atomic::AtomicUsize;
397 use std::sync::atomic::Ordering;
398
399 use allocator_api2::alloc::AllocError;
400 use allocator_api2::alloc::Allocator;
401 use allocator_api2::alloc::Global;
402 use rstest::rstest;
403 use vortex_error::VortexResult;
404 use vortex_error::vortex_err;
405
406 use crate::Alignment;
407 use crate::BufferAllocatorRef;
408 use crate::BufferMut;
409
410 #[derive(Clone, Debug, Default)]
411 struct TrackingAllocator {
412 state: Arc<TrackingState>,
413 }
414
415 #[derive(Debug, Default)]
416 struct TrackingState {
417 allocations: AtomicUsize,
418 deallocations: AtomicUsize,
419 grows: AtomicUsize,
420 alignment: AtomicUsize,
421 }
422
423 unsafe impl Allocator for TrackingAllocator {
425 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
426 self.state.allocations.fetch_add(1, Ordering::Relaxed);
427 self.state
428 .alignment
429 .store(layout.align(), Ordering::Relaxed);
430 Global.allocate(layout)
431 }
432
433 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
434 self.state.deallocations.fetch_add(1, Ordering::Relaxed);
435 unsafe { Global.deallocate(ptr, layout) }
437 }
438
439 unsafe fn grow(
440 &self,
441 ptr: NonNull<u8>,
442 old_layout: Layout,
443 new_layout: Layout,
444 ) -> Result<NonNull<[u8]>, AllocError> {
445 self.state.grows.fetch_add(1, Ordering::Relaxed);
446 unsafe { Global.grow(ptr, old_layout, new_layout) }
448 }
449 }
450
451 #[test]
452 fn allocator_identity() {
453 let static_allocator = BufferAllocatorRef::statically_allocated();
454 assert!(static_allocator.ptr_eq(&BufferAllocatorRef::statically_allocated()));
455
456 let custom_allocator = BufferAllocatorRef::new(TrackingAllocator::default());
457 assert!(custom_allocator.ptr_eq(&custom_allocator.clone()));
458 assert!(!custom_allocator.ptr_eq(&static_allocator));
459 assert!(!custom_allocator.ptr_eq(&BufferAllocatorRef::new(TrackingAllocator::default())));
460 }
461
462 #[test]
463 fn allocation_lives_until_last_view() {
464 let allocator = TrackingAllocator::default();
465 let state = Arc::clone(&allocator.state);
466 let buffer = BufferAllocatorRef::new(allocator)
467 .copy_from([1u32, 2, 3, 4])
468 .freeze();
469 let view = buffer.slice(0..2);
470
471 assert_eq!(state.allocations.load(Ordering::Relaxed), 1);
472 assert_eq!(
473 state.alignment.load(Ordering::Relaxed),
474 Alignment::of::<u8>().as_usize()
475 );
476 drop(buffer);
477 assert_eq!(state.deallocations.load(Ordering::Relaxed), 0);
478 drop(view);
479 assert_eq!(state.deallocations.load(Ordering::Relaxed), 1);
480 }
481
482 #[rstest]
483 fn buffer_growth_uses_allocator_grow(#[values(4, 64, 4096)] alignment: usize) {
484 let allocator = TrackingAllocator::default();
485 let state = Arc::clone(&allocator.state);
486 let alignment = Alignment::new(alignment);
487 let mut buffer =
488 BufferAllocatorRef::new(allocator).with_capacity_aligned::<u32>(1, alignment);
489 let initial_capacity = buffer.capacity();
490 buffer.extend(std::iter::repeat_n(7, initial_capacity));
491
492 buffer.push(u32::MAX);
493 assert!(alignment.is_ptr_aligned(buffer.as_ptr()));
494
495 assert_eq!(&buffer[..initial_capacity], vec![7; initial_capacity]);
496 assert_eq!(buffer[initial_capacity], u32::MAX);
497 assert_eq!(state.allocations.load(Ordering::Relaxed), 1);
498 assert_eq!(state.deallocations.load(Ordering::Relaxed), 0);
499 assert_eq!(state.grows.load(Ordering::Relaxed), 1);
500
501 drop(buffer);
502 assert_eq!(state.deallocations.load(Ordering::Relaxed), 1);
503 }
504
505 #[test]
506 fn zero_capacity_does_not_allocate() {
507 let allocator = TrackingAllocator::default();
508 let state = Arc::clone(&allocator.state);
509 let mut buffer = BufferAllocatorRef::new(allocator).with_capacity::<u32>(0);
510
511 assert_eq!(buffer.capacity(), 0);
512 assert!(Alignment::DEFAULT_ALIGNMENT.is_offset_aligned(buffer.as_ptr().addr()));
513 assert_eq!(state.allocations.load(Ordering::Relaxed), 0);
514
515 buffer.push(42);
516
517 assert_eq!(buffer.as_slice(), [42]);
518 assert_eq!(state.allocations.load(Ordering::Relaxed), 1);
519 assert_eq!(state.grows.load(Ordering::Relaxed), 0);
520 }
521
522 #[test]
523 fn empty_buffers_preserve_allocator_without_allocating() -> VortexResult<()> {
524 let allocator = TrackingAllocator::default();
525 let state = Arc::clone(&allocator.state);
526 let allocator = BufferAllocatorRef::new(allocator);
527 let buffer = BufferMut::<u32>::zeroed_in(0, allocator.clone());
528 let buffer = buffer.freeze();
529 let copy = buffer.clone().into_mut();
530 assert!(copy.allocation.allocator().ptr_eq(&allocator));
531 let mut buffer = buffer
532 .try_into_mut()
533 .map_err(|_| vortex_err!("unique buffer"))?;
534 buffer.reserve(0);
535 assert!(buffer.is_empty());
536 assert!(buffer.allocation.allocator().ptr_eq(&allocator));
537 drop((copy, buffer));
538 assert_eq!(state.allocations.load(Ordering::Relaxed), 0);
539 assert_eq!(state.grows.load(Ordering::Relaxed), 0);
540 assert_eq!(state.deallocations.load(Ordering::Relaxed), 0);
541 Ok(())
542 }
543
544 #[test]
545 fn shared_into_mut_preserves_allocator() {
546 let allocator = TrackingAllocator::default();
547 let state = Arc::clone(&allocator.state);
548 let allocator = BufferAllocatorRef::new(allocator);
549 let original = allocator.copy_from([1u32, 2, 3]).freeze();
550 let mut copy = original.clone().into_mut();
551 assert!(copy.allocation.allocator().ptr_eq(&allocator));
552 copy[0] = 42;
553 assert_eq!(original.as_slice(), [1, 2, 3]);
554 assert_eq!(copy.as_slice(), [42, 2, 3]);
555 assert_eq!(state.allocations.load(Ordering::Relaxed), 2);
556 drop(copy);
557 assert_eq!(state.deallocations.load(Ordering::Relaxed), 1);
558 drop(original);
559 assert_eq!(state.deallocations.load(Ordering::Relaxed), 2);
560 }
561
562 #[derive(Debug, Default)]
566 struct MovingAllocator {
567 calls: AtomicUsize,
568 shrinks: AtomicUsize,
569 }
570
571 impl MovingAllocator {
572 const REAL_ALIGN: usize = 1 << 16;
573
574 fn real_block(ptr: NonNull<u8>, layout: Layout) -> (NonNull<u8>, Layout) {
576 let shift = ptr.addr().get() % Self::REAL_ALIGN;
577 let real = unsafe { ptr.sub(shift) };
579 let real_layout = Layout::from_size_align(layout.size() + shift, Self::REAL_ALIGN)
580 .unwrap_or_else(|_| unreachable!("allocate checked this layout"));
581 (real, real_layout)
582 }
583 }
584
585 unsafe impl Allocator for MovingAllocator {
588 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
589 let call = self.calls.fetch_add(1, Ordering::Relaxed);
590 let shift = layout.align() * (1 + call % 7);
591 if shift >= Self::REAL_ALIGN {
592 return Err(AllocError);
593 }
594 let real_layout = Layout::from_size_align(layout.size() + shift, Self::REAL_ALIGN)
595 .map_err(|_| AllocError)?;
596 let real = Global.allocate(real_layout)?.cast::<u8>();
597 let ptr = unsafe { real.add(shift) };
599 Ok(NonNull::slice_from_raw_parts(ptr, layout.size()))
600 }
601
602 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
603 let (real, real_layout) = Self::real_block(ptr, layout);
604 unsafe { Global.deallocate(real, real_layout) }
606 }
607
608 unsafe fn shrink(
609 &self,
610 ptr: NonNull<u8>,
611 old_layout: Layout,
612 new_layout: Layout,
613 ) -> Result<NonNull<[u8]>, AllocError> {
614 self.shrinks.fetch_add(1, Ordering::Relaxed);
615 let new = self.allocate(new_layout)?;
616 unsafe {
618 std::ptr::copy_nonoverlapping(
619 ptr.as_ptr(),
620 new.cast::<u8>().as_ptr(),
621 new_layout.size(),
622 );
623 self.deallocate(ptr, old_layout);
624 }
625 Ok(new)
626 }
627 }
628
629 fn assert_shrunk<T: Copy + PartialEq + std::fmt::Debug>(
630 buffer: &BufferMut<T>,
631 expected: &[T],
632 alignment: Alignment,
633 ) {
634 assert_eq!(buffer.as_slice(), expected);
635 assert!(alignment.is_ptr_aligned(buffer.as_ptr()));
636 assert!(buffer.capacity() >= buffer.len());
637 let max_bytes = buffer.len() * size_of::<T>()
639 + alignment
640 .as_usize()
641 .max(Alignment::DEFAULT_ALIGNMENT.as_usize())
642 + alignment.as_usize()
643 - 1;
644 assert!(buffer.allocation.size() <= max_bytes.max(1));
645 }
646
647 #[rstest]
648 fn shrink_to_fit_realigns_moved_blocks(
649 #[values(8, 64, 4096)] alignment: usize,
650 #[values(1, 3, 1000)] len: u64,
651 ) {
652 let allocator = Arc::new(MovingAllocator::default());
653 let alignment = Alignment::new(alignment);
654 let mut buffer = BufferMut::<u64>::empty_aligned_in(
656 alignment,
657 BufferAllocatorRef::new(ArcAllocator(Arc::clone(&allocator))),
658 );
659 let expected: Vec<u64> = (0..len).collect();
660 buffer.reserve(8192);
661 buffer.extend_from_slice(&expected);
662 assert!(buffer.allocation.alignment() < alignment.as_usize());
663
664 buffer.shrink_to_fit();
665
666 assert_shrunk(&buffer, &expected, alignment);
667 assert_eq!(allocator.shrinks.load(Ordering::Relaxed), 1);
668 buffer.push(u64::MAX);
669 assert_eq!(buffer[expected.len()], u64::MAX);
670 assert!(alignment.is_ptr_aligned(buffer.as_ptr()));
671 }
672
673 #[rstest]
674 fn shrink_to_fit_with_global(
675 #[values(2, 8, 64, 4096)] alignment: usize,
676 #[values(0, 1, 1000)] len: u16,
677 ) {
678 let alignment = Alignment::new(alignment);
679 let mut buffer = BufferMut::<u16>::with_capacity_aligned(1 << 16, alignment);
680 let expected: Vec<u16> = (0..len).collect();
681 buffer.extend_from_slice(&expected);
682
683 buffer.shrink_to_fit();
684
685 assert_shrunk(&buffer, &expected, alignment);
686 assert_eq!(buffer.alignment(), alignment);
687 }
688
689 #[test]
690 fn shrink_to_fit_drops_slice_prefix() -> VortexResult<()> {
691 let allocator = Arc::new(MovingAllocator::default());
692 let alignment = Alignment::new(64);
693 let values: Vec<u64> = (0..1024).collect();
694 let buffer = BufferMut::<u64>::copy_from_aligned_in(
695 &values,
696 alignment,
697 BufferAllocatorRef::new(ArcAllocator(Arc::clone(&allocator))),
698 )
699 .freeze()
700 .slice(512..520);
701 let mut buffer = buffer
702 .try_into_mut()
703 .map_err(|_| vortex_err!("unique buffer"))?;
704
705 buffer.shrink_to_fit();
706
707 assert_shrunk(&buffer, &values[512..520], alignment);
708 assert_eq!(allocator.shrinks.load(Ordering::Relaxed), 0);
710 assert_eq!(allocator.calls.load(Ordering::Relaxed), 2);
711 Ok(())
712 }
713
714 #[test]
715 fn shrink_to_fit_trims_small_slack() {
716 let allocator = Arc::new(MovingAllocator::default());
717 let mut buffer = BufferMut::<u8>::with_capacity_preferred_aligned_in(
719 200,
720 Alignment::of::<u8>(),
721 None,
722 BufferAllocatorRef::new(ArcAllocator(Arc::clone(&allocator))),
723 );
724 buffer.extend_from_slice(&[7; 100]);
725
726 buffer.shrink_to_fit();
727
728 assert_eq!(buffer.as_slice(), [7; 100]);
729 assert_eq!(buffer.allocation.size(), 100);
730 assert_eq!(allocator.shrinks.load(Ordering::Relaxed), 1);
731 }
732
733 #[rstest]
734 fn shrink_to_fit_is_idempotent(#[values(1, 64)] alignment: usize) {
735 let allocator = Arc::new(MovingAllocator::default());
736 let alignment = Alignment::new(alignment);
737 let mut buffer = BufferAllocatorRef::new(ArcAllocator(Arc::clone(&allocator)))
738 .with_capacity_aligned::<u8>(1024, alignment);
739 buffer.extend_from_slice(&[1, 2, 3]);
740
741 buffer.shrink_to_fit();
742 let ptr = buffer.as_ptr();
743 buffer.shrink_to_fit();
744
745 assert_eq!(buffer.as_slice(), [1, 2, 3]);
746 assert_eq!(buffer.as_ptr(), ptr);
747 assert_eq!(allocator.shrinks.load(Ordering::Relaxed), 1);
748 }
749
750 #[derive(Debug)]
752 struct ArcAllocator(Arc<MovingAllocator>);
753
754 unsafe impl Allocator for ArcAllocator {
756 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
757 self.0.allocate(layout)
758 }
759
760 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
761 unsafe { self.0.deallocate(ptr, layout) }
763 }
764
765 unsafe fn shrink(
766 &self,
767 ptr: NonNull<u8>,
768 old_layout: Layout,
769 new_layout: Layout,
770 ) -> Result<NonNull<[u8]>, AllocError> {
771 unsafe { self.0.shrink(ptr, old_layout, new_layout) }
773 }
774 }
775}