1#![no_std]
19
20pub mod alignment;
21pub mod reader;
22mod sealed;
23#[cfg(test)]
24mod tests;
25
26extern crate alloc;
27
28use crate::alignment::{Align1, Align16, Align4096, Alignment, AtLeast};
29use crate::reader::SharedAlignedBufferReader;
30use alloc::alloc::{alloc, alloc_zeroed, dealloc, handle_alloc_error, realloc};
31use core::alloc::Layout;
32use core::marker::PhantomData;
33use core::mem::{ManuallyDrop, MaybeUninit};
34use core::ops::{Bound, Deref, DerefMut, RangeBounds};
35use core::ptr::NonNull;
36use core::sync::atomic::{AtomicUsize, Ordering, fence};
37use core::{fmt, hint, ptr, slice};
38use stable_deref_trait::{CloneStableDeref, StableDeref};
39use yoke::CloneableCart;
40
41#[inline(always)]
43const fn align_usize<A>() -> usize
44where
45 A: Alignment,
46{
47 A::ALIGN as usize
49}
50
51const MIN_ALLOCATION_ALIGNMENT: usize = align_usize::<Align16>();
53const MAX_ALIGNMENT: usize = align_usize::<Align4096>();
55const MAX_CAPACITY: u32 = if usize::BITS < u64::BITS {
57 ((isize::MAX.cast_unsigned() / MAX_ALIGNMENT - 1) * MAX_ALIGNMENT) as u32
60} else {
61 u32::MAX
62};
63
64#[derive(Debug, Copy, Clone, Eq, PartialEq)]
66pub enum AllocationError {
67 CapacityOverflow,
69 AllocatorError {
71 layout: Layout,
73 },
74}
75
76impl fmt::Display for AllocationError {
77 #[inline]
78 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79 match self {
80 Self::CapacityOverflow => {
81 write!(f, "Capacity is larger than the largest supported capacity")
82 }
83 Self::AllocatorError { layout } => {
84 write!(f, "Allocator failed to allocate {} bytes", layout.size())
85 }
86 }
87 }
88}
89
90impl core::error::Error for AllocationError {}
91
92#[cold]
94fn handle_error<T>(error: AllocationError) -> T {
95 match error {
96 AllocationError::CapacityOverflow => {
97 panic!("Capacity is larger than the largest supported capacity")
98 }
99 AllocationError::AllocatorError { layout } => handle_alloc_error(layout),
100 }
101}
102
103#[repr(C, align(16))]
105struct Header {
106 strong_count: AtomicUsize,
108 capacity: u32,
110 alignment_log2: u32,
112}
113
114const _: () = {
115 assert!(size_of::<Header>() == MIN_ALLOCATION_ALIGNMENT);
116 assert!(align_of::<Header>() == MIN_ALLOCATION_ALIGNMENT);
117 assert!(align_usize::<Align16>() >= align_of::<u128>());
119};
120
121const _: () = {
122 let Ok(_) = Layout::from_size_align(
125 MAX_ALIGNMENT + (MAX_CAPACITY as usize).next_multiple_of(MAX_ALIGNMENT),
126 MAX_ALIGNMENT,
127 ) else {
128 panic!("The largest capacity can't be allocated");
129 };
130 assert!(
132 MAX_CAPACITY == u32::MAX
133 || Layout::from_size_align(
134 MAX_ALIGNMENT + (MAX_CAPACITY as usize + 1).next_multiple_of(MAX_ALIGNMENT),
135 MAX_ALIGNMENT,
136 )
137 .is_err()
138 );
139};
140
141#[repr(C, align(4096))]
147struct EmptyAllocation {
148 padding: [u8; MAX_ALIGNMENT - size_of::<Header>()],
149 header: Header,
150}
151
152const _: () = {
153 assert!(align_of::<EmptyAllocation>() == MAX_ALIGNMENT);
154 assert!(size_of::<EmptyAllocation>() == MAX_ALIGNMENT);
155};
156
157static EMPTY_ALLOCATION: EmptyAllocation = EmptyAllocation {
158 padding: [0; _],
159 header: Header {
160 strong_count: AtomicUsize::new(0),
161 capacity: 0,
162 alignment_log2: MAX_ALIGNMENT.ilog2(),
163 },
164};
165
166static EMPTY_INNER_BUFFER: InnerBuffer = InnerBuffer::EMPTY;
168
169#[derive(Debug)]
170struct InnerBuffer {
171 buffer: NonNull<u8>,
173 offset: u32,
176 len: u32,
177}
178
179unsafe impl Send for InnerBuffer {}
181unsafe impl Sync for InnerBuffer {}
183
184impl InnerBuffer {
185 const EMPTY: Self = Self {
187 buffer: unsafe {
190 NonNull::from_ref(&EMPTY_ALLOCATION)
191 .cast::<u8>()
192 .byte_add(size_of::<EmptyAllocation>())
193 },
194 offset: 0,
195 len: 0,
196 };
197
198 #[inline(always)]
206 #[cfg_attr(
207 target_pointer_width = "64",
208 expect(
209 clippy::absurd_extreme_comparisons,
210 reason = "`MAX_CAPACITY` is `u32::MAX` where `usize` is 64-bit"
211 )
212 )]
213 fn layout(capacity: u32, alignment: usize) -> Option<Layout> {
214 if capacity > MAX_CAPACITY {
217 return None;
218 }
219 let size = (capacity as usize)
222 .checked_next_multiple_of(alignment)?
223 .checked_add(alignment)?;
224 Layout::from_size_align(size, alignment).ok()
225 }
226
227 #[inline(always)]
232 unsafe fn allocated_layout(&self) -> Layout {
233 let alignment = self.alignment();
234 let size = alignment + (self.total_capacity() as usize).next_multiple_of(alignment);
235 unsafe { Layout::from_size_align_unchecked(size, alignment) }
237 }
238
239 #[inline(always)]
249 fn allocate(total_capacity: u32, alignment: usize, offset: u32) -> Self {
250 Self::try_allocate(total_capacity, alignment, offset).unwrap_or_else(handle_error)
251 }
252
253 #[inline(always)]
255 fn try_allocate(
256 total_capacity: u32,
257 alignment: usize,
258 offset: u32,
259 ) -> Result<Self, AllocationError> {
260 unsafe { Self::try_allocate_with(total_capacity, alignment, offset, alloc) }
262 }
263
264 #[inline(always)]
266 fn try_allocate_zeroed(
267 total_capacity: u32,
268 alignment: usize,
269 offset: u32,
270 ) -> Result<Self, AllocationError> {
271 unsafe { Self::try_allocate_with(total_capacity, alignment, offset, alloc_zeroed) }
273 }
274
275 #[inline(always)]
278 unsafe fn try_allocate_with(
279 total_capacity: u32,
280 alignment: usize,
281 offset: u32,
282 allocator: unsafe fn(Layout) -> *mut u8,
283 ) -> Result<Self, AllocationError> {
284 debug_assert!(
285 alignment.is_power_of_two()
286 && (MIN_ALLOCATION_ALIGNMENT..=MAX_ALIGNMENT).contains(&alignment),
287 "Unsupported alignment {alignment}"
288 );
289 debug_assert!(
290 offset <= total_capacity,
291 "Offset {offset} is larger than capacity {total_capacity}"
292 );
293
294 if total_capacity == 0 {
295 return Ok(Self::EMPTY);
296 }
297
298 let layout =
299 Self::layout(total_capacity, alignment).ok_or(AllocationError::CapacityOverflow)?;
300 let allocation = unsafe { allocator(layout) };
302 let allocation =
303 NonNull::new(allocation).ok_or(AllocationError::AllocatorError { layout })?;
304 let data = unsafe { allocation.byte_add(alignment) };
307
308 unsafe {
311 data.cast::<Header>().sub(1).write(Header {
312 strong_count: AtomicUsize::new(1),
313 capacity: total_capacity,
314 alignment_log2: alignment.ilog2(),
315 });
316 }
317
318 Ok(Self {
319 buffer: unsafe { data.byte_add(offset as usize) },
321 offset,
322 len: 0,
323 })
324 }
325
326 #[inline(always)]
336 fn resize(&mut self, capacity: u32, min_alignment: usize) {
337 self.try_resize(capacity, min_alignment)
338 .unwrap_or_else(handle_error);
339 }
340
341 #[inline(always)]
343 fn try_resize(&mut self, capacity: u32, min_alignment: usize) -> Result<(), AllocationError> {
344 if self.total_capacity() == 0 {
345 *self = Self::try_allocate(capacity, min_alignment.max(MIN_ALLOCATION_ALIGNMENT), 0)?;
347 return Ok(());
348 }
349
350 let total_capacity = self
351 .offset
352 .checked_add(capacity)
353 .ok_or(AllocationError::CapacityOverflow)?;
354
355 let alignment = self.alignment();
356 let reallocate_in_place = alignment == MIN_ALLOCATION_ALIGNMENT
361 && min_alignment <= MIN_ALLOCATION_ALIGNMENT
362 && self.offset == 0;
363 if !reallocate_in_place {
364 let misalignment = u32::try_from(self.offset as usize % min_alignment)
368 .expect("Smaller than alignment, which is at most 4096; qed");
369 let offset = self.offset - misalignment;
370 let new = Self::try_allocate(
371 total_capacity - (self.offset - offset),
372 alignment.max(min_alignment),
373 offset,
374 )?;
375 unsafe {
377 self.replace(new);
378 }
379 return Ok(());
380 }
381
382 let new_layout =
383 Self::layout(total_capacity, alignment).ok_or(AllocationError::CapacityOverflow)?;
384 let old_layout = unsafe { self.allocated_layout() };
386
387 let allocation = unsafe {
390 realloc(
391 self.allocation_ptr().as_ptr(),
392 old_layout,
393 new_layout.size(),
394 )
395 };
396 let allocation = NonNull::new(allocation)
398 .ok_or(AllocationError::AllocatorError { layout: new_layout })?;
399 self.buffer = unsafe { allocation.byte_add(alignment) };
402 unsafe {
404 (*self.header_ptr().as_ptr()).capacity = total_capacity;
405 }
406
407 Ok(())
408 }
409
410 #[inline(always)]
417 unsafe fn replace(&mut self, mut new: Self) {
418 debug_assert!(new.capacity() >= self.len, "Not enough capacity");
419
420 unsafe {
423 new.buffer
424 .copy_from_nonoverlapping(self.buffer, self.len as usize);
425 }
426 new.len = self.len;
427 if self.total_capacity() != 0 {
428 unsafe {
430 self.deallocate();
431 }
432 }
433 *self = new;
434 }
435
436 #[inline(always)]
441 unsafe fn move_to_offset(&mut self, offset: u32) {
442 debug_assert!(
443 u64::from(offset) + u64::from(self.len) <= u64::from(self.total_capacity()),
444 "Contents don't fit"
445 );
446
447 let buffer = unsafe { self.data_ptr().byte_add(offset as usize) };
449 unsafe {
452 buffer.copy_from(self.buffer, self.len as usize);
453 }
454 self.buffer = buffer;
455 self.offset = offset;
456 }
457
458 #[inline(always)]
463 fn set_offset(&mut self, offset: u32, alignment: u32) -> bool {
464 let Some(advance) = offset.checked_sub(self.offset) else {
465 return false;
466 };
467 if advance > self.len || !advance.is_multiple_of(alignment) {
468 return false;
469 }
470
471 self.buffer = unsafe { self.buffer.byte_add(advance as usize) };
473 self.offset = offset;
474 self.len -= advance;
475 true
476 }
477
478 #[inline(always)]
484 unsafe fn deallocate(&self) {
485 unsafe {
488 dealloc(self.allocation_ptr().as_ptr(), self.allocated_layout());
489 }
490 }
491
492 #[inline(always)]
495 fn copy(&self, alignment: usize) -> Self {
496 let mut new = Self::allocate(self.len, alignment.max(MIN_ALLOCATION_ALIGNMENT), 0);
497 unsafe {
499 new.buffer
500 .copy_from_nonoverlapping(self.buffer, self.len as usize);
501 }
502 new.len = self.len;
503 new
504 }
505
506 #[inline(always)]
509 fn slice(&self, start: u32, len: u32) -> Self {
510 debug_assert!(
511 len != 0 && u64::from(start) + u64::from(len) <= u64::from(self.len),
512 "Slice out of bounds"
513 );
514 self.increment_strong_count();
515
516 Self {
517 buffer: unsafe { self.buffer.byte_add(start as usize) },
519 offset: self.offset + start,
520 len,
521 }
522 }
523
524 #[inline(always)]
526 fn increment_strong_count(&self) {
527 let strong_count = self.strong_count_ref();
528 let old_count = strong_count.fetch_add(1, Ordering::Relaxed);
529 if usize::BITS < u64::BITS && old_count > isize::MAX.cast_unsigned() {
532 strong_count.fetch_sub(1, Ordering::Relaxed);
533 panic!("Too many clones of a shared aligned buffer");
534 }
535 }
536
537 #[inline(always)]
538 const fn data_ptr(&self) -> NonNull<u8> {
539 unsafe { self.buffer.byte_sub(self.offset as usize) }
541 }
542
543 #[inline(always)]
544 const fn header_ptr(&self) -> NonNull<Header> {
545 unsafe { self.data_ptr().cast::<Header>().sub(1) }
547 }
548
549 #[inline(always)]
550 const fn header(&self) -> &Header {
551 unsafe { self.header_ptr().as_ref() }
553 }
554
555 #[inline(always)]
556 fn allocation_ptr(&self) -> NonNull<u8> {
557 unsafe { self.data_ptr().byte_sub(self.alignment()) }
560 }
561
562 #[inline(always)]
563 const fn len(&self) -> u32 {
564 self.len
565 }
566
567 #[inline(always)]
569 unsafe fn set_len(&mut self, len: u32) {
570 debug_assert!(
571 len <= self.capacity(),
572 "Too many bytes {} > {}",
573 len,
574 self.capacity()
575 );
576 self.len = len;
577 }
578
579 #[inline(always)]
580 const fn offset(&self) -> u32 {
581 self.offset
582 }
583
584 #[inline(always)]
586 const fn capacity(&self) -> u32 {
587 self.total_capacity() - self.offset
588 }
589
590 #[inline(always)]
592 const fn total_capacity(&self) -> u32 {
593 self.header().capacity
594 }
595
596 #[inline(always)]
599 fn allocation_alignment(&self, content_alignment: u32) -> u32 {
600 if ptr::eq(self.header(), &raw const EMPTY_ALLOCATION.header) {
601 content_alignment.max(Align16::ALIGN)
602 } else {
603 2_u32.pow(self.alignment_log2())
604 }
605 }
606
607 #[inline(always)]
608 const fn alignment(&self) -> usize {
609 2_usize.pow(self.alignment_log2())
610 }
611
612 #[inline(always)]
613 const fn alignment_log2(&self) -> u32 {
614 let alignment_log2 = self.header().alignment_log2;
615 unsafe { hint::assert_unchecked(alignment_log2 <= MAX_ALIGNMENT.ilog2()) }
618 alignment_log2
619 }
620
621 #[inline(always)]
622 const fn strong_count_ref(&self) -> &AtomicUsize {
623 &self.header().strong_count
624 }
625
626 #[inline(always)]
627 const fn as_slice(&self) -> &[u8] {
628 let len = self.len() as usize;
629 unsafe { slice::from_raw_parts(self.as_ptr(), len) }
631 }
632
633 #[inline(always)]
634 const fn as_mut_slice(&mut self) -> &mut [u8] {
635 let len = self.len() as usize;
636 unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), len) }
638 }
639
640 #[inline(always)]
641 const fn as_ptr(&self) -> *const u8 {
642 self.buffer.as_ptr().cast_const()
643 }
644
645 #[inline(always)]
646 const fn as_mut_ptr(&mut self) -> *mut u8 {
647 self.buffer.as_ptr()
648 }
649
650 #[inline(always)]
651 fn is_aligned_to(&self, alignment: usize) -> bool {
652 self.buffer.addr().get().is_multiple_of(alignment)
653 }
654}
655
656#[derive(Debug)]
664pub struct OwnedAlignedBuffer<A = Align16>
665where
666 A: Alignment,
667{
668 inner: InnerBuffer,
669 alignment: PhantomData<A>,
670}
671
672impl<A> Drop for OwnedAlignedBuffer<A>
673where
674 A: Alignment,
675{
676 #[inline(always)]
677 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
678 fn drop(&mut self) {
679 if self.inner.total_capacity() != 0 {
682 unsafe {
684 self.inner.deallocate();
685 }
686 }
687 }
688}
689
690impl<A> Deref for OwnedAlignedBuffer<A>
691where
692 A: Alignment,
693{
694 type Target = [u8];
695
696 #[inline(always)]
697 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
698 fn deref(&self) -> &Self::Target {
699 self.as_slice()
700 }
701}
702
703impl<A> DerefMut for OwnedAlignedBuffer<A>
704where
705 A: Alignment,
706{
707 #[inline(always)]
708 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
709 fn deref_mut(&mut self) -> &mut Self::Target {
710 self.as_mut_slice()
711 }
712}
713
714unsafe impl<A> StableDeref for OwnedAlignedBuffer<A> where A: Alignment {}
716
717impl<A> sealed::Sealed for OwnedAlignedBuffer<A> where A: Alignment {}
718
719impl<A> AlignedBuffer for OwnedAlignedBuffer<A>
720where
721 A: Alignment,
722{
723 type Alignment = A;
724
725 #[inline(always)]
726 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
727 fn len(&self) -> u32 {
728 self.len()
729 }
730
731 #[inline(always)]
732 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
733 fn is_empty(&self) -> bool {
734 self.is_empty()
735 }
736
737 #[inline(always)]
738 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
739 fn offset(&self) -> u32 {
740 self.offset()
741 }
742
743 #[inline(always)]
744 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
745 fn set_offset(&mut self, offset: u32) -> bool {
746 self.set_offset(offset)
747 }
748
749 #[inline(always)]
750 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
751 fn allocation_alignment(&self) -> u32 {
752 self.allocation_alignment()
753 }
754
755 #[inline(always)]
756 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
757 fn into_shared(self) -> SharedAlignedBuffer<Self::Alignment> {
758 self.into_shared()
759 }
760}
761
762impl<A> Default for OwnedAlignedBuffer<A>
763where
764 A: Alignment,
765{
766 #[inline(always)]
767 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
768 fn default() -> Self {
769 Self::EMPTY
770 }
771}
772
773impl<A> Clone for OwnedAlignedBuffer<A>
774where
775 A: Alignment,
776{
777 #[inline(always)]
779 fn clone(&self) -> Self {
780 Self::from_inner(
781 self.inner
782 .copy(self.inner.alignment().max(align_usize::<A>())),
783 )
784 }
785}
786
787impl<A> OwnedAlignedBuffer<A>
788where
789 A: Alignment,
790{
791 pub const MAX_CAPACITY: u32 = MAX_CAPACITY;
797
798 pub const ALIGN: u32 = A::ALIGN;
802
803 pub const EMPTY: Self = Self::from_inner(InnerBuffer::EMPTY);
805
806 #[inline(always)]
814 pub fn with_capacity(capacity: u32) -> Self {
815 Self::try_with_capacity(capacity).unwrap_or_else(handle_error)
816 }
817
818 #[inline(always)]
822 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
823 pub fn try_with_capacity(capacity: u32) -> Result<Self, AllocationError> {
824 InnerBuffer::try_allocate(
825 capacity,
826 align_usize::<A>().max(MIN_ALLOCATION_ALIGNMENT),
827 0,
828 )
829 .map(Self::from_inner)
830 }
831
832 #[inline(always)]
839 pub fn from_bytes(bytes: &[u8]) -> Self {
840 let Ok(len) = u32::try_from(bytes.len()) else {
841 panic!("Too many bytes {}", bytes.len());
842 };
843
844 let mut instance = Self::with_capacity(len);
845 instance.copy_from_slice(bytes);
846 instance
847 }
848
849 #[inline(always)]
859 pub fn zeroed(len: u32) -> Self {
860 Self::try_zeroed(len).unwrap_or_else(handle_error)
861 }
862
863 #[inline(always)]
868 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
869 pub fn try_zeroed(len: u32) -> Result<Self, AllocationError> {
870 let mut instance = Self::from_inner(InnerBuffer::try_allocate_zeroed(
871 len,
872 align_usize::<A>().max(MIN_ALLOCATION_ALIGNMENT),
873 0,
874 )?);
875 unsafe {
877 instance.set_len(len);
878 }
879 Ok(instance)
880 }
881
882 #[inline(always)]
883 const fn from_inner(inner: InnerBuffer) -> Self {
884 Self {
885 inner,
886 alignment: PhantomData,
887 }
888 }
889
890 #[inline(always)]
891 fn into_inner(self) -> InnerBuffer {
892 let this = ManuallyDrop::new(self);
893 unsafe { (&raw const this.inner).read() }
895 }
896
897 #[inline(always)]
899 fn assume_aligned(&self) {
900 unsafe { hint::assert_unchecked(self.inner.is_aligned_to(align_usize::<A>())) }
902 }
903
904 #[inline(always)]
905 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
906 pub fn as_slice(&self) -> &[u8] {
907 self.assume_aligned();
908 self.inner.as_slice()
909 }
910
911 #[inline(always)]
912 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
913 pub fn as_mut_slice(&mut self) -> &mut [u8] {
914 self.assume_aligned();
915 self.inner.as_mut_slice()
916 }
917
918 #[inline(always)]
920 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
921 pub fn as_byte_ptr(&self) -> *const u8 {
922 self.assume_aligned();
923 self.inner.as_ptr()
924 }
925
926 #[inline(always)]
928 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
929 pub fn as_mut_byte_ptr(&mut self) -> *mut u8 {
930 self.assume_aligned();
931 self.inner.as_mut_ptr()
932 }
933
934 #[inline(always)]
937 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
938 pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<u8>] {
939 let len = self.len() as usize;
940 let spare_capacity = (self.capacity() - self.len()) as usize;
941 unsafe {
944 slice::from_raw_parts_mut(
945 self.as_mut_byte_ptr().add(len).cast::<MaybeUninit<u8>>(),
946 spare_capacity,
947 )
948 }
949 }
950
951 #[inline(always)]
955 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
956 pub fn into_shared(self) -> SharedAlignedBuffer<A> {
957 if self.is_empty() {
958 return SharedAlignedBuffer::EMPTY;
959 }
960
961 SharedAlignedBuffer::from_inner(self.into_inner())
963 }
964
965 #[inline(always)]
977 #[must_use = "The buffer is dropped otherwise"]
978 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
979 pub fn into_start_align<B>(self) -> OwnedAlignedBuffer<B>
980 where
981 A: AtLeast<B>,
982 B: Alignment,
983 {
984 OwnedAlignedBuffer::from_inner(self.into_inner())
985 }
986
987 #[inline(always)]
991 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
992 pub fn try_into_start_align<B>(self) -> Result<OwnedAlignedBuffer<B>, Self>
993 where
994 B: Alignment,
995 {
996 if self.inner.is_aligned_to(align_usize::<B>()) {
997 Ok(OwnedAlignedBuffer::from_inner(self.into_inner()))
998 } else {
999 Err(self)
1000 }
1001 }
1002
1003 #[inline(always)]
1011 pub fn ensure_capacity(&mut self, capacity: u32) {
1012 self.try_ensure_capacity(capacity)
1013 .unwrap_or_else(handle_error);
1014 }
1015
1016 #[inline(always)]
1022 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1023 pub fn try_ensure_capacity(&mut self, capacity: u32) -> Result<(), AllocationError> {
1024 if capacity > self.capacity() {
1025 self.inner.try_resize(capacity, align_usize::<A>())?;
1026 }
1027
1028 Ok(())
1029 }
1030
1031 #[inline(always)]
1036 pub fn copy_from_slice(&mut self, bytes: &[u8]) {
1037 let Ok(len) = u32::try_from(bytes.len()) else {
1038 panic!("Too many bytes {}", bytes.len());
1039 };
1040
1041 if len > self.capacity() {
1042 self.inner.resize(
1044 len.max(
1045 self.capacity()
1046 .saturating_mul(2)
1047 .min(MAX_CAPACITY - self.offset()),
1048 ),
1049 align_usize::<A>(),
1050 );
1051 }
1052
1053 unsafe {
1056 self.as_mut_byte_ptr()
1057 .copy_from_nonoverlapping(bytes.as_ptr(), bytes.len());
1058
1059 self.inner.set_len(len);
1060 }
1061 }
1062
1063 #[inline(always)]
1068 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1069 pub fn append(&mut self, bytes: &[u8]) -> Result<(), AllocationError> {
1070 let new_len = u32::try_from(bytes.len())
1071 .ok()
1072 .and_then(|len| self.len().checked_add(len))
1073 .filter(|&new_len| new_len <= MAX_CAPACITY - self.offset())
1075 .ok_or(AllocationError::CapacityOverflow)?;
1076
1077 if new_len > self.capacity() {
1078 self.inner.try_resize(
1080 new_len.max(
1081 self.capacity()
1082 .saturating_mul(2)
1083 .min(MAX_CAPACITY - self.offset()),
1084 ),
1085 align_usize::<A>(),
1086 )?;
1087 }
1088
1089 unsafe {
1092 self.as_mut_byte_ptr()
1093 .add(self.len() as usize)
1094 .copy_from_nonoverlapping(bytes.as_ptr(), bytes.len());
1095
1096 self.inner.set_len(new_len);
1097 }
1098
1099 Ok(())
1100 }
1101
1102 #[inline]
1107 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1108 pub fn pad_to_alignment<B>(&mut self) -> Result<(), AllocationError>
1109 where
1110 B: Alignment,
1111 {
1112 static ZEROES: [u8; MAX_ALIGNMENT] = [0; MAX_ALIGNMENT];
1114
1115 let misalignment = self.len() % B::ALIGN;
1116 let padding = if misalignment == 0 {
1117 0
1118 } else {
1119 B::ALIGN - misalignment
1120 };
1121 self.append(&ZEROES[..padding as usize])
1122 }
1123
1124 #[inline(always)]
1125 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1126 pub fn is_empty(&self) -> bool {
1127 self.inner.len() == 0
1128 }
1129
1130 #[inline(always)]
1131 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1132 pub fn len(&self) -> u32 {
1133 self.inner.len()
1134 }
1135
1136 #[inline(always)]
1138 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1139 pub fn capacity(&self) -> u32 {
1140 self.inner.capacity()
1141 }
1142
1143 #[inline(always)]
1145 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1146 pub fn offset(&self) -> u32 {
1147 self.inner.offset()
1148 }
1149
1150 #[inline(always)]
1157 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1158 pub fn allocation_alignment(&self) -> u32 {
1159 self.inner.allocation_alignment(A::ALIGN)
1160 }
1161
1162 #[inline(always)]
1166 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1167 pub fn truncate(&mut self, len: u32) {
1168 if len < self.len() {
1169 self.inner.len = len;
1170 }
1171 }
1172
1173 #[inline(always)]
1180 #[must_use = "Check for invalid offset"]
1181 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1182 pub fn set_offset(&mut self, offset: u32) -> bool {
1183 self.inner.set_offset(offset, A::ALIGN)
1184 }
1185
1186 #[inline]
1193 #[must_use = "The buffer is dropped otherwise"]
1194 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1195 pub fn into_empty<B>(mut self) -> OwnedAlignedBuffer<B>
1196 where
1197 B: Alignment,
1198 {
1199 if self.inner.total_capacity() == 0 || self.inner.alignment() < align_usize::<B>() {
1200 return OwnedAlignedBuffer::EMPTY;
1201 }
1202
1203 self.inner.len = 0;
1204 unsafe {
1206 self.inner.move_to_offset(0);
1207 }
1208 OwnedAlignedBuffer::from_inner(self.into_inner())
1210 }
1211
1212 #[inline]
1222 #[must_use = "Check for invalid offset or capacity"]
1223 #[cfg_attr(
1224 target_pointer_width = "64",
1225 expect(
1226 clippy::absurd_extreme_comparisons,
1227 reason = "`MAX_CAPACITY` is `u32::MAX` where `usize` is 64-bit"
1228 )
1229 )]
1230 pub fn relocate<AA>(&mut self, offset: u32, capacity: u32) -> bool
1231 where
1232 AA: AtLeast<A> + AtLeast<Align16>,
1233 {
1234 if !offset.is_multiple_of(A::ALIGN) {
1235 return false;
1236 }
1237 let capacity = capacity.max(self.len());
1238 let Some(total_capacity) = offset.checked_add(capacity) else {
1239 return false;
1240 };
1241 if total_capacity > MAX_CAPACITY {
1242 return false;
1243 }
1244
1245 if self.inner.total_capacity() >= total_capacity
1246 && self.inner.alignment() >= align_usize::<AA>()
1247 {
1248 unsafe {
1250 self.inner.move_to_offset(offset);
1251 }
1252 } else {
1253 unsafe {
1255 self.inner.replace(InnerBuffer::allocate(
1256 total_capacity,
1257 align_usize::<AA>(),
1258 offset,
1259 ));
1260 }
1261 }
1262
1263 true
1264 }
1265
1266 #[inline]
1273 #[must_use = "The buffer is dropped otherwise"]
1274 pub fn realign<B>(mut self) -> OwnedAlignedBuffer<B>
1275 where
1276 B: Alignment,
1277 {
1278 let misalignment = u32::try_from(self.inner.buffer.addr().get() % align_usize::<B>())
1279 .expect("Smaller than alignment, which is at most 4096; qed");
1280 if misalignment != 0 {
1281 let alignment = B::ALIGN;
1282 let len = self.len();
1283 let total_capacity = self.inner.total_capacity();
1284 let maybe_offset = self.offset().checked_sub(misalignment).or_else(|| {
1287 self.offset()
1288 .checked_add(alignment - misalignment)
1289 .filter(|&offset| {
1290 u64::from(offset) + u64::from(len) <= u64::from(total_capacity)
1291 })
1292 });
1293
1294 if let Some(offset) = maybe_offset {
1295 unsafe {
1297 self.inner.move_to_offset(offset);
1298 }
1299 } else {
1300 let new = InnerBuffer::allocate(
1301 self.capacity(),
1302 align_usize::<B>().max(MIN_ALLOCATION_ALIGNMENT),
1303 0,
1304 );
1305 unsafe {
1307 self.inner.replace(new);
1308 }
1309 }
1310 }
1311
1312 OwnedAlignedBuffer::from_inner(self.into_inner())
1313 }
1314
1315 #[inline(always)]
1320 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1321 pub unsafe fn set_len(&mut self, new_len: u32) {
1322 unsafe {
1324 self.inner.set_len(new_len);
1325 }
1326 }
1327}
1328
1329impl<A> OwnedAlignedBuffer<A>
1330where
1331 A: AtLeast<Align16>,
1332{
1333 #[inline(always)]
1338 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1339 pub fn as_u128_slice(&self) -> &[u128] {
1340 let len = self.len() as usize / size_of::<u128>();
1341 unsafe { slice::from_raw_parts(self.as_ptr(), len) }
1345 }
1346
1347 #[inline(always)]
1348 #[expect(
1349 clippy::cast_ptr_alignment,
1350 reason = "Contents are aligned to at least `u128`"
1351 )]
1352 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1353 pub fn as_ptr(&self) -> *const u128 {
1354 self.as_byte_ptr().cast::<u128>()
1355 }
1356
1357 #[inline(always)]
1358 #[expect(
1359 clippy::cast_ptr_alignment,
1360 reason = "Contents are aligned to at least `u128`"
1361 )]
1362 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1363 pub fn as_mut_ptr(&mut self) -> *mut u128 {
1364 self.as_mut_byte_ptr().cast::<u128>()
1365 }
1366}
1367
1368#[derive(Debug)]
1375#[repr(transparent)]
1376pub struct SharedAlignedBuffer<A = Align16>
1377where
1378 A: Alignment,
1379{
1380 inner: InnerBuffer,
1383 alignment: PhantomData<A>,
1384}
1385
1386impl<A> Default for SharedAlignedBuffer<A>
1387where
1388 A: Alignment,
1389{
1390 #[inline(always)]
1391 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1392 fn default() -> Self {
1393 Self::EMPTY
1394 }
1395}
1396
1397impl<A> Clone for SharedAlignedBuffer<A>
1398where
1399 A: Alignment,
1400{
1401 #[inline(always)]
1402 #[cfg_attr(
1404 all(feature = "no-panic", target_pointer_width = "64"),
1405 no_panic::no_panic
1406 )]
1407 fn clone(&self) -> Self {
1408 if !self.is_empty() {
1409 self.inner.increment_strong_count();
1410 }
1411
1412 Self::from_inner(InnerBuffer {
1413 buffer: self.inner.buffer,
1414 offset: self.inner.offset,
1415 len: self.inner.len,
1416 })
1417 }
1418}
1419
1420impl<A> Drop for SharedAlignedBuffer<A>
1421where
1422 A: Alignment,
1423{
1424 #[inline(always)]
1425 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1426 fn drop(&mut self) {
1427 if !self.is_empty()
1428 && self
1429 .inner
1430 .strong_count_ref()
1431 .fetch_sub(1, Ordering::Release)
1432 == 1
1433 {
1434 fence(Ordering::Acquire);
1437 unsafe {
1439 self.inner.deallocate();
1440 }
1441 }
1442 }
1443}
1444
1445impl<A> Deref for SharedAlignedBuffer<A>
1446where
1447 A: Alignment,
1448{
1449 type Target = [u8];
1450
1451 #[inline(always)]
1452 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1453 fn deref(&self) -> &Self::Target {
1454 self.as_slice()
1455 }
1456}
1457
1458unsafe impl<A> StableDeref for SharedAlignedBuffer<A> where A: Alignment {}
1460unsafe impl<A> CloneStableDeref for SharedAlignedBuffer<A> where A: Alignment {}
1462unsafe impl<A> CloneableCart for SharedAlignedBuffer<A> where A: Alignment {}
1464
1465impl<A> sealed::Sealed for SharedAlignedBuffer<A> where A: Alignment {}
1466
1467impl<A> AlignedBuffer for SharedAlignedBuffer<A>
1468where
1469 A: Alignment,
1470{
1471 type Alignment = A;
1472
1473 #[inline(always)]
1474 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1475 fn len(&self) -> u32 {
1476 self.len()
1477 }
1478
1479 #[inline(always)]
1480 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1481 fn is_empty(&self) -> bool {
1482 self.is_empty()
1483 }
1484
1485 #[inline(always)]
1486 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1487 fn offset(&self) -> u32 {
1488 self.offset()
1489 }
1490
1491 #[inline(always)]
1492 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1493 fn set_offset(&mut self, offset: u32) -> bool {
1494 self.set_offset(offset)
1495 }
1496
1497 #[inline(always)]
1498 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1499 fn allocation_alignment(&self) -> u32 {
1500 self.allocation_alignment()
1501 }
1502
1503 #[inline(always)]
1504 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1505 fn into_shared(self) -> SharedAlignedBuffer<Self::Alignment> {
1506 self
1507 }
1508}
1509
1510impl<A> SharedAlignedBuffer<A>
1511where
1512 A: Alignment,
1513{
1514 pub const ALIGN: u32 = A::ALIGN;
1518
1519 pub const EMPTY: Self = Self::from_inner(InnerBuffer::EMPTY);
1521
1522 #[inline(always)]
1529 pub fn from_bytes(bytes: &[u8]) -> Self {
1530 OwnedAlignedBuffer::from_bytes(bytes).into_shared()
1531 }
1532
1533 #[inline(always)]
1534 const fn from_inner(inner: InnerBuffer) -> Self {
1535 Self {
1536 inner,
1537 alignment: PhantomData,
1538 }
1539 }
1540
1541 #[inline(always)]
1542 fn into_inner(self) -> InnerBuffer {
1543 let this = ManuallyDrop::new(self);
1544 unsafe { (&raw const this.inner).read() }
1546 }
1547
1548 #[inline(always)]
1550 fn assume_aligned(&self) {
1551 unsafe { hint::assert_unchecked(self.inner.is_aligned_to(align_usize::<A>())) }
1553 }
1554
1555 #[inline(always)]
1557 pub const fn empty_ref() -> &'static Self {
1558 unsafe { &*(&raw const EMPTY_INNER_BUFFER).cast::<Self>() }
1561 }
1562
1563 #[inline(always)]
1569 pub fn into_owned(self) -> OwnedAlignedBuffer<A> {
1570 match self.try_into_owned() {
1571 Ok(owned) => owned,
1572 Err(shared) => OwnedAlignedBuffer::from_inner(
1573 shared
1574 .inner
1575 .copy(shared.inner.alignment().max(align_usize::<A>())),
1576 ),
1577 }
1578 }
1579
1580 #[inline(always)]
1582 fn is_last_reference(&self) -> bool {
1583 self.inner.strong_count_ref().load(Ordering::Acquire) == 1
1587 }
1588
1589 #[inline(always)]
1594 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1595 pub fn try_into_owned(self) -> Result<OwnedAlignedBuffer<A>, Self> {
1596 if self.is_empty() {
1597 return Ok(OwnedAlignedBuffer::EMPTY);
1598 }
1599
1600 if self.is_last_reference() {
1601 Ok(OwnedAlignedBuffer::from_inner(self.into_inner()))
1603 } else {
1604 Err(self)
1605 }
1606 }
1607
1608 #[inline(always)]
1613 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1614 pub fn get_mut(&mut self) -> Option<&mut [u8]> {
1615 if self.is_empty() {
1616 return Some(&mut []);
1617 }
1618
1619 if self.is_last_reference() {
1620 self.assume_aligned();
1621 Some(self.inner.as_mut_slice())
1623 } else {
1624 None
1625 }
1626 }
1627
1628 #[inline]
1634 pub fn make_mut(&mut self) -> &mut [u8] {
1635 if self.is_empty() {
1636 return &mut [];
1637 }
1638
1639 if !self.is_last_reference() {
1640 *self = Self::from_inner(
1641 self.inner
1642 .copy(self.inner.alignment().max(align_usize::<A>())),
1643 );
1644 }
1645
1646 self.assume_aligned();
1647 self.inner.as_mut_slice()
1650 }
1651
1652 #[inline]
1662 #[must_use = "The buffer is dropped otherwise"]
1663 pub fn into_standalone(self) -> Self {
1664 if self.offset() == 0 && self.len() == self.inner.total_capacity() {
1665 self
1666 } else {
1667 Self::from_inner(self.inner.copy(align_usize::<A>()))
1668 }
1669 }
1670
1671 #[inline]
1678 #[must_use = "The slice is dropped otherwise"]
1679 #[cfg_attr(
1681 all(feature = "no-panic", target_pointer_width = "64"),
1682 no_panic::no_panic
1683 )]
1684 pub fn get_slice<R>(&self, range: R) -> Option<SharedAlignedBuffer<Align1>>
1685 where
1686 R: RangeBounds<u32>,
1687 {
1688 let start = match range.start_bound() {
1689 Bound::Included(&start) => start,
1690 Bound::Excluded(&start) => start.checked_add(1)?,
1691 Bound::Unbounded => 0,
1692 };
1693 let end = match range.end_bound() {
1694 Bound::Included(&end) => end.checked_add(1)?,
1695 Bound::Excluded(&end) => end,
1696 Bound::Unbounded => self.len(),
1697 };
1698 if start > end || end > self.len() {
1699 return None;
1700 }
1701 if start == end {
1702 return Some(SharedAlignedBuffer::EMPTY);
1703 }
1704
1705 Some(SharedAlignedBuffer::from_inner(
1706 self.inner.slice(start, end - start),
1707 ))
1708 }
1709
1710 #[inline]
1719 #[must_use = "Buffers are dropped otherwise"]
1720 #[cfg_attr(
1722 all(feature = "no-panic", target_pointer_width = "64"),
1723 no_panic::no_panic
1724 )]
1725 pub fn split_at(&self, mid: u32) -> Option<(Self, SharedAlignedBuffer<Align1>)> {
1726 let rest = self.get_slice(mid..)?;
1727 let first = if mid == 0 {
1728 Self::EMPTY
1729 } else {
1730 Self::from_inner(self.inner.slice(0, mid))
1731 };
1732
1733 Some((first, rest))
1734 }
1735
1736 #[inline(always)]
1738 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1739 pub fn reader(&self) -> SharedAlignedBufferReader<'_, A> {
1740 SharedAlignedBufferReader::new(self)
1741 }
1742
1743 #[inline(always)]
1748 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1749 pub fn truncate(&mut self, len: u32) {
1750 if len == 0 {
1751 *self = Self::EMPTY;
1752 } else if len < self.len() {
1753 self.inner.len = len;
1754 }
1755 }
1756
1757 #[inline(always)]
1765 #[must_use = "Check for invalid offset"]
1766 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1767 pub fn set_offset(&mut self, offset: u32) -> bool {
1768 if offset.checked_sub(self.offset()) == Some(self.len())
1769 && self.len().is_multiple_of(A::ALIGN)
1770 {
1771 *self = Self::EMPTY;
1772 return true;
1773 }
1774
1775 self.inner.set_offset(offset, A::ALIGN)
1776 }
1777
1778 #[inline(always)]
1780 #[must_use = "The buffer is dropped otherwise"]
1781 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1782 pub fn into_start_align<B>(self) -> SharedAlignedBuffer<B>
1783 where
1784 A: AtLeast<B>,
1785 B: Alignment,
1786 {
1787 SharedAlignedBuffer::from_inner(self.into_inner())
1788 }
1789
1790 #[inline(always)]
1794 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1795 pub fn try_into_start_align<B>(self) -> Result<SharedAlignedBuffer<B>, Self>
1796 where
1797 B: Alignment,
1798 {
1799 if self.inner.is_aligned_to(align_usize::<B>()) {
1800 Ok(SharedAlignedBuffer::from_inner(self.into_inner()))
1801 } else {
1802 Err(self)
1803 }
1804 }
1805
1806 #[inline(always)]
1807 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1808 pub fn as_slice(&self) -> &[u8] {
1809 self.assume_aligned();
1810 self.inner.as_slice()
1811 }
1812
1813 #[inline(always)]
1815 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1816 pub fn as_byte_ptr(&self) -> *const u8 {
1817 self.assume_aligned();
1818 self.inner.as_ptr()
1819 }
1820
1821 #[inline(always)]
1822 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1823 pub fn is_empty(&self) -> bool {
1824 self.inner.len() == 0
1825 }
1826
1827 #[inline(always)]
1828 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1829 pub fn len(&self) -> u32 {
1830 self.inner.len()
1831 }
1832
1833 #[inline(always)]
1835 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1836 pub fn capacity(&self) -> u32 {
1837 self.inner.capacity()
1838 }
1839
1840 #[inline(always)]
1842 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1843 pub fn offset(&self) -> u32 {
1844 self.inner.offset()
1845 }
1846
1847 #[inline(always)]
1853 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1854 pub fn allocation_alignment(&self) -> u32 {
1855 self.inner.allocation_alignment(A::ALIGN)
1856 }
1857}
1858
1859impl<A> SharedAlignedBuffer<A>
1860where
1861 A: AtLeast<Align16>,
1862{
1863 #[inline(always)]
1864 #[expect(
1865 clippy::cast_ptr_alignment,
1866 reason = "Contents are aligned to at least `u128`"
1867 )]
1868 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1869 pub fn as_ptr(&self) -> *const u128 {
1870 self.as_byte_ptr().cast::<u128>()
1871 }
1872}
1873
1874pub trait AlignedBuffer:
1879 sealed::Sealed + Deref<Target = [u8]> + StableDeref + fmt::Debug + Send + Sync + 'static
1880{
1881 type Alignment: Alignment;
1883
1884 fn len(&self) -> u32;
1886
1887 fn is_empty(&self) -> bool;
1889
1890 fn offset(&self) -> u32;
1892
1893 #[must_use = "Check for invalid offset"]
1896 fn set_offset(&mut self, offset: u32) -> bool;
1897
1898 fn allocation_alignment(&self) -> u32;
1900
1901 fn into_shared(self) -> SharedAlignedBuffer<Self::Alignment>;
1903}