Skip to main content

ab_aligned_buffer/
lib.rs

1//! Efficient abstraction for aligned memory buffers with both owned and shared variants.
2//!
3//! [`OwnedAlignedBuffer`] represents an aligned memory location that can be modified.
4//!
5//! [`SharedAlignedBuffer`] can't be modified but supports cheap reference-counting clones (like
6//! `Arc`, but much more efficient).
7//!
8//! Contents of buffers are aligned to 16 bytes by default, which is the largest alignment required
9//! by primitive types. Alignment of the contents is a part of the type of the buffer (see
10//! [`Alignment`]). Allocations can be aligned more strictly than that, for example, to 4096 bytes
11//! for direct I/O.
12//!
13//! A buffer handle is 16 bytes on 64-bit platforms (pointer, offset and length, while capacity and
14//! the reference counter are stored in the allocation), so it is cheap to pass by value.
15//!
16//! Does not require a standard library (`no_std`) but does require allocator and atomics.
17
18#![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/// Alignment `A` in bytes as `usize`
42#[inline(always)]
43const fn align_usize<A>() -> usize
44where
45    A: Alignment,
46{
47    // Lossless, alignment is at most 4096
48    A::ALIGN as usize
49}
50
51/// The smallest alignment of allocations, which is also the size of the header
52const MIN_ALLOCATION_ALIGNMENT: usize = align_usize::<Align16>();
53/// The strictest supported alignment of allocations
54const MAX_ALIGNMENT: usize = align_usize::<Align4096>();
55/// See [`OwnedAlignedBuffer::MAX_CAPACITY`]
56const MAX_CAPACITY: u32 = if usize::BITS < u64::BITS {
57    // Space for the header is reserved in front of the contents, which is as large as the
58    // alignment
59    ((isize::MAX.cast_unsigned() / MAX_ALIGNMENT - 1) * MAX_ALIGNMENT) as u32
60} else {
61    u32::MAX
62};
63
64/// Error of a fallible allocation, for example of [`OwnedAlignedBuffer::try_with_capacity()`]
65#[derive(Debug, Copy, Clone, Eq, PartialEq)]
66pub enum AllocationError {
67    /// Requested capacity is larger than [`OwnedAlignedBuffer::MAX_CAPACITY`]
68    CapacityOverflow,
69    /// Allocator failed to allocate memory
70    AllocatorError {
71        /// Layout of the allocation that failed
72        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/// Handles an error of an infallible allocation the same way as standard library collections do
93#[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/// Header of every allocation, stored right before the contents of the buffer
104#[repr(C, align(16))]
105struct Header {
106    /// The number of shared buffers referencing the allocation, owned buffers don't use it
107    strong_count: AtomicUsize,
108    /// Capacity of the buffer in bytes
109    capacity: u32,
110    /// Base 2 logarithm of the alignment of the allocation
111    alignment_log2: u32,
112}
113
114const _: () = {
115    assert!(size_of::<Header>() == MIN_ALLOCATION_ALIGNMENT);
116    assert!(align_of::<Header>() == MIN_ALLOCATION_ALIGNMENT);
117    // Contents of buffers aligned to `Align16` are accessed as `u128`s
118    assert!(align_usize::<Align16>() >= align_of::<u128>());
119};
120
121const _: () = {
122    // The size of an allocation for the largest capacity and alignment, computed like in
123    // `InnerBuffer::layout()`, is valid
124    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    // A larger capacity either doesn't fit into `u32` or its allocation is too large
131    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/// Memory of empty buffers, which are not backed by an allocation.
142///
143/// Empty buffers point to the end of it, right after the header, which makes them aligned to any
144/// supported alignment. Empty owned buffers have zero capacity and empty shared buffers don't hold
145/// a reference, so nothing ever modifies it.
146#[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
166/// Empty buffer referenced by [`SharedAlignedBuffer::empty_ref()`] for any alignment
167static EMPTY_INNER_BUFFER: InnerBuffer = InnerBuffer::EMPTY;
168
169#[derive(Debug)]
170struct InnerBuffer {
171    /// The first byte of the contents
172    buffer: NonNull<u8>,
173    /// Offset of the contents from the beginning of the data region of the allocation, which has
174    /// the header right before it
175    offset: u32,
176    len: u32,
177}
178
179// SAFETY: Heap-allocated memory buffer can be used from any thread
180unsafe impl Send for InnerBuffer {}
181// SAFETY: Heap-allocated memory buffer can be used from any thread
182unsafe impl Sync for InnerBuffer {}
183
184impl InnerBuffer {
185    /// Empty buffer that is not backed by an allocation
186    const EMPTY: Self = Self {
187        // SAFETY: Right after the header at the end of the empty allocation, which is the same as
188        // for allocated buffers
189        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    /// Layout of an allocation for a specified capacity and alignment.
199    ///
200    /// The header is in front of the data region, and the size of the allocation is a multiple of
201    /// alignment, which allocators handle most efficiently.
202    ///
203    /// Returns `None` if the capacity is larger than [`OwnedAlignedBuffer::MAX_CAPACITY`] or the
204    /// allocation would be too large.
205    #[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        // The largest capacity is the same for all alignments, even if allocations with smaller
215        // alignment could be slightly larger
216        if capacity > MAX_CAPACITY {
217            return None;
218        }
219        // With a narrower `usize`, a `u32` capacity can overflow the size or exceed `isize::MAX`,
220        // the largest size of an allocation
221        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    /// Layout of the allocation that backs the buffer.
228    ///
229    /// # Safety
230    /// The buffer must be backed by an allocation (have non-zero total capacity).
231    #[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        // SAFETY: Allocated with the same layout before, which was checked by `Self::layout()`
236        unsafe { Layout::from_size_align_unchecked(size, alignment) }
237    }
238
239    /// Allocates a new buffer with a header in front of the data region, contents start at
240    /// `offset` within the data region.
241    ///
242    /// `alignment` must be a supported alignment that is not smaller than
243    /// `MIN_ALLOCATION_ALIGNMENT`, `offset` must not be larger than `total_capacity`. Zero total
244    /// capacity results in an empty buffer that is not backed by an allocation.
245    ///
246    /// # Panics
247    /// If `total_capacity` is larger than [`OwnedAlignedBuffer::MAX_CAPACITY`] or allocation fails
248    #[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    /// Fallible version of [`Self::allocate()`]
254    #[inline(always)]
255    fn try_allocate(
256        total_capacity: u32,
257        alignment: usize,
258        offset: u32,
259    ) -> Result<Self, AllocationError> {
260        // SAFETY: Global allocator's function
261        unsafe { Self::try_allocate_with(total_capacity, alignment, offset, alloc) }
262    }
263
264    /// Allocates a new buffer with zeroed data region, see [`Self::try_allocate()`] for details
265    #[inline(always)]
266    fn try_allocate_zeroed(
267        total_capacity: u32,
268        alignment: usize,
269        offset: u32,
270    ) -> Result<Self, AllocationError> {
271        // SAFETY: Global allocator's function
272        unsafe { Self::try_allocate_with(total_capacity, alignment, offset, alloc_zeroed) }
273    }
274
275    /// # Safety
276    /// `allocator` must allocate memory with global allocator
277    #[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        // SAFETY: Non-zero size, allocates with global allocator, guaranteed by the caller
301        let allocation = unsafe { allocator(layout) };
302        let allocation =
303            NonNull::new(allocation).ok_or(AllocationError::AllocatorError { layout })?;
304        // SAFETY: The data region starts right after the space reserved for the header at the
305        // beginning of the allocation, which is as large as the alignment
306        let data = unsafe { allocation.byte_add(alignment) };
307
308        // SAFETY: The header is right before the data region and is correctly aligned, since the
309        // data region is aligned to at least the size of the header
310        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            // SAFETY: Offset is within the data region
320            buffer: unsafe { data.byte_add(offset as usize) },
321            offset,
322            len: 0,
323        })
324    }
325
326    /// Changes capacity of the buffer while preserving its contents and their offset, the buffer
327    /// must not be shared.
328    ///
329    /// The new allocation is aligned to at least `min_alignment`, which must be a supported
330    /// alignment.
331    ///
332    /// # Panics
333    /// If `capacity` with offset is larger than [`OwnedAlignedBuffer::MAX_CAPACITY`] or allocation
334    /// fails
335    #[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    /// Fallible version of [`Self::resize()`], the buffer is not changed on error
342    #[inline(always)]
343    fn try_resize(&mut self, capacity: u32, min_alignment: usize) -> Result<(), AllocationError> {
344        if self.total_capacity() == 0 {
345            // Empty buffer is not backed by an allocation, and it has no contents to preserve
346            *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        // `realloc()` is only used for allocations aligned to 16 bytes when that is enough for the
357        // contents: it can't change the alignment, and standard library's `realloc()` copies the
358        // whole allocation for larger alignments anyway. Contents with an offset are not
359        // reallocated either, since bytes before them would be copied too
360        let reallocate_in_place = alignment == MIN_ALLOCATION_ALIGNMENT
361            && min_alignment <= MIN_ALLOCATION_ALIGNMENT
362            && self.offset == 0;
363        if !reallocate_in_place {
364            // Copy just the contents into a new allocation. Contents with an offset in an
365            // allocation with smaller alignment could only be aligned to `min_alignment` by chance,
366            // so the offset is reduced to keep the alignment then.
367            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            // SAFETY: Not shared, new buffer has enough capacity for the contents
376            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        // SAFETY: Non-zero capacity checked above
385        let old_layout = unsafe { self.allocated_layout() };
386
387        // SAFETY: Allocated with global allocator and `old_layout`, non-zero new size that is at
388        // most `isize::MAX` when rounded up to the alignment (checked by `Layout` above)
389        let allocation = unsafe {
390            realloc(
391                self.allocation_ptr().as_ptr(),
392                old_layout,
393                new_layout.size(),
394            )
395        };
396        // The old allocation is not changed if reallocation fails
397        let allocation = NonNull::new(allocation)
398            .ok_or(AllocationError::AllocatorError { layout: new_layout })?;
399        // SAFETY: The data region starts right after the space reserved for the header at the
400        // beginning of the allocation, which is as large as the alignment, and offset is zero
401        self.buffer = unsafe { allocation.byte_add(alignment) };
402        // SAFETY: Reallocation preserved the header, and the buffer is not shared
403        unsafe {
404            (*self.header_ptr().as_ptr()).capacity = total_capacity;
405        }
406
407        Ok(())
408    }
409
410    /// Replaces the buffer with `new`, moving the contents into it and deallocating the current
411    /// allocation.
412    ///
413    /// # Safety
414    /// The buffer must not be shared, the new buffer must be a different allocation with enough
415    /// capacity for the contents.
416    #[inline(always)]
417    unsafe fn replace(&mut self, mut new: Self) {
418        debug_assert!(new.capacity() >= self.len, "Not enough capacity");
419
420        // SAFETY: Different allocations, `len` bytes are initialized and fit into the new
421        // capacity, guaranteed by the caller
422        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            // SAFETY: Backed by an allocation and not shared, guaranteed by the caller
429            unsafe {
430                self.deallocate();
431            }
432        }
433        *self = new;
434    }
435
436    /// Moves contents to a different offset within the same allocation.
437    ///
438    /// # Safety
439    /// The buffer must not be shared, the contents must fit into the data region at a new offset.
440    #[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        // SAFETY: Within the data region, guaranteed by the caller
448        let buffer = unsafe { self.data_ptr().byte_add(offset as usize) };
449        // SAFETY: Both ranges are within the same allocation, `copy_from` handles overlapping
450        // ranges, `len` bytes are initialized
451        unsafe {
452            buffer.copy_from(self.buffer, self.len as usize);
453        }
454        self.buffer = buffer;
455        self.offset = offset;
456    }
457
458    /// Moves the beginning of the contents forward to `offset` without moving any bytes, see
459    /// [`OwnedAlignedBuffer::set_offset()`].
460    ///
461    /// The contents are aligned to `alignment` in memory and stay aligned to it.
462    #[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        // SAFETY: Within the contents as checked above
472        self.buffer = unsafe { self.buffer.byte_add(advance as usize) };
473        self.offset = offset;
474        self.len -= advance;
475        true
476    }
477
478    /// Deallocates the buffer.
479    ///
480    /// # Safety
481    /// The buffer must be backed by an allocation (have non-zero total capacity) and not be
482    /// referenced anymore.
483    #[inline(always)]
484    unsafe fn deallocate(&self) {
485        // SAFETY: Allocated with global allocator and this layout, guaranteed by the caller to be
486        // backed by an allocation that is not referenced anymore
487        unsafe {
488            dealloc(self.allocation_ptr().as_ptr(), self.allocated_layout());
489        }
490    }
491
492    /// Creates an owned copy of the contents without offset, aligned to `alignment`, which must be
493    /// a supported alignment
494    #[inline(always)]
495    fn copy(&self, alignment: usize) -> Self {
496        let mut new = Self::allocate(self.len, alignment.max(MIN_ALLOCATION_ALIGNMENT), 0);
497        // SAFETY: Different allocations, `len` bytes are initialized and fit into the new capacity
498        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    /// Creates a new reference to a part of the contents of a shared buffer, which must be
507    /// non-empty and within the contents
508    #[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            // SAFETY: Within the contents
518            buffer: unsafe { self.buffer.byte_add(start as usize) },
519            offset: self.offset + start,
520            len,
521        }
522    }
523
524    /// Increments reference counter of a shared buffer, which must not be empty
525    #[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        // Leaked clones could wrap a counter narrower than 64 bits around, and a drop would then
530        // free the buffer while other clones still use it
531        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        // SAFETY: Contents are at offset within the data region
540        unsafe { self.buffer.byte_sub(self.offset as usize) }
541    }
542
543    #[inline(always)]
544    const fn header_ptr(&self) -> NonNull<Header> {
545        // SAFETY: The header is right before the data region
546        unsafe { self.data_ptr().cast::<Header>().sub(1) }
547    }
548
549    #[inline(always)]
550    const fn header(&self) -> &Header {
551        // SAFETY: The header is initialized in the constructor and lives as long as the buffer
552        unsafe { self.header_ptr().as_ref() }
553    }
554
555    #[inline(always)]
556    fn allocation_ptr(&self) -> NonNull<u8> {
557        // SAFETY: The data region starts right after the space reserved for the header at the
558        // beginning of the allocation, which is as large as the alignment
559        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    /// `len` bytes must be initialized
568    #[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    /// Capacity from the beginning of the contents
585    #[inline(always)]
586    const fn capacity(&self) -> u32 {
587        self.total_capacity() - self.offset
588    }
589
590    /// Capacity of the whole data region
591    #[inline(always)]
592    const fn total_capacity(&self) -> u32 {
593        self.header().capacity
594    }
595
596    /// Alignment of the allocation, or the alignment an empty buffer without an allocation grows
597    /// into for contents aligned to `content_alignment`
598    #[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        // SAFETY: The header stores the binary logarithm of a supported alignment, which is never
616        // larger than `MAX_ALIGNMENT`
617        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        // SAFETY: Not null and length is a protected invariant of the implementation
630        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        // SAFETY: Not null and length is a protected invariant of the implementation
637        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/// Owned aligned buffer for executor purposes.
657///
658/// See [`SharedAlignedBuffer`] for a version that can be cheaply cloned while reusing the original
659/// allocation.
660///
661/// Contents are aligned to `A`, by default 16 bytes (128 bits), which is the largest alignment
662/// required by primitive types and by extension any type that implements `TrivialType`/`IoType`.
663#[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        // Owned buffer is not shared, so the reference counter is not used, and an empty buffer
680        // with zero capacity is not backed by an allocation
681        if self.inner.total_capacity() != 0 {
682            // SAFETY: Backed by an allocation and not shared
683            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
714// SAFETY: Heap-allocated data structure, points to the same memory if moved
715unsafe 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    /// Allocates as much as the length of the buffer with the same alignment, without offset
778    #[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    /// The largest capacity of a buffer.
792    ///
793    /// It is `u32::MAX` where `usize` is 64-bit, and smaller where `usize` is 32-bit, since an
794    /// allocation can't be larger than `isize::MAX` bytes. The allocator may still fail to allocate
795    /// a buffer that large.
796    pub const MAX_CAPACITY: u32 = MAX_CAPACITY;
797
798    /// Alignment of the contents in bytes.
799    ///
800    /// The allocation can be aligned more strictly, see [`Self::allocation_alignment()`].
801    pub const ALIGN: u32 = A::ALIGN;
802
803    /// Empty buffer that is not backed by an allocation
804    pub const EMPTY: Self = Self::from_inner(InnerBuffer::EMPTY);
805
806    /// Create a new instance with specified capacity.
807    ///
808    /// Allocation is aligned to the alignment of the contents, but at least 16 bytes.
809    ///
810    /// # Panics
811    /// If `capacity` is larger than [`Self::MAX_CAPACITY`] or allocation fails, see
812    /// [`Self::try_with_capacity()`] for a fallible version
813    #[inline(always)]
814    pub fn with_capacity(capacity: u32) -> Self {
815        Self::try_with_capacity(capacity).unwrap_or_else(handle_error)
816    }
817
818    /// Create a new instance with specified capacity, see [`Self::with_capacity()`] for details.
819    ///
820    /// Returns an error if `capacity` is larger than [`Self::MAX_CAPACITY`] or allocation fails.
821    #[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    /// Create a new instance from provided bytes.
833    ///
834    /// Allocation is aligned to the alignment of the contents, but at least 16 bytes.
835    ///
836    /// # Panics
837    /// If `bytes.len()` is larger than [`Self::MAX_CAPACITY`]
838    #[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    /// Create a new instance of specified length filled with zeroes.
850    ///
851    /// Allocation is aligned to the alignment of the contents, but at least 16 bytes. Zeroed memory
852    /// is allocated directly, which is cheaper than writing zeroes into it, especially for large
853    /// buffers.
854    ///
855    /// # Panics
856    /// If `len` is larger than [`Self::MAX_CAPACITY`] or allocation fails, see
857    /// [`Self::try_zeroed()`] for a fallible version
858    #[inline(always)]
859    pub fn zeroed(len: u32) -> Self {
860        Self::try_zeroed(len).unwrap_or_else(handle_error)
861    }
862
863    /// Create a new instance of specified length filled with zeroes, see [`Self::zeroed()`] for
864    /// details.
865    ///
866    /// Returns an error if `len` is larger than [`Self::MAX_CAPACITY`] or allocation fails.
867    #[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        // SAFETY: The whole data region is zeroed, which is a valid initialized value
876        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        // SAFETY: Moved out of `ManuallyDrop` that is never used again
894        unsafe { (&raw const this.inner).read() }
895    }
896
897    /// Tells the compiler that the contents are aligned to `A`, which it can't see otherwise
898    #[inline(always)]
899    fn assume_aligned(&self) {
900        // SAFETY: Contents are aligned to `A`, which is an invariant of the type
901        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    /// Pointer to the first byte of the contents
919    #[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    /// Mutable pointer to the first byte of the contents
927    #[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    /// Spare capacity of the buffer after its contents, which can be written to and then included
935    /// in the contents with [`Self::set_len()`]
936    #[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        // SAFETY: Spare capacity is within the allocation right after the contents, the buffer is
942        // not shared, and bytes are treated as potentially uninitialized
943        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    /// Convert into shared buffer.
952    ///
953    /// Allocation is reused, except for empty buffer, which doesn't need an allocation.
954    #[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        // The reference counter is `1` since owned buffer is not shared
962        SharedAlignedBuffer::from_inner(self.into_inner())
963    }
964
965    /// Convert into a buffer with a weaker alignment of the contents, which is free.
966    ///
967    /// Conversion to a stricter alignment doesn't compile, see [`Self::try_into_start_align()`]
968    /// instead:
969    /// ```compile_fail
970    /// use ab_aligned_buffer::OwnedAlignedBuffer;
971    /// use ab_aligned_buffer::alignment::Align4096;
972    ///
973    /// // Contents aligned to 16 bytes are not necessarily aligned to 4096 bytes
974    /// let _ = OwnedAlignedBuffer::with_capacity(1).into_start_align::<Align4096>();
975    /// ```
976    #[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    /// Convert into a buffer with a different alignment of the contents, which is free.
988    ///
989    /// Returns the buffer back if its contents are not aligned to `B`.
990    #[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    /// Ensure capacity of the buffer is at least `capacity`.
1004    ///
1005    /// Will re-allocate if necessary.
1006    ///
1007    /// # Panics
1008    /// If `capacity` with [`Self::offset()`] is larger than [`OwnedAlignedBuffer::MAX_CAPACITY`]
1009    /// or allocation fails, see [`Self::try_ensure_capacity()`] for a fallible version
1010    #[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    /// Ensure capacity of the buffer is at least `capacity`, see [`Self::ensure_capacity()`] for
1017    /// details.
1018    ///
1019    /// Returns an error and leaves the buffer unchanged if `capacity` with [`Self::offset()`] is
1020    /// larger than [`OwnedAlignedBuffer::MAX_CAPACITY`] or allocation fails.
1021    #[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    /// Will re-allocate if capacity is not enough to store provided bytes.
1032    ///
1033    /// # Panics
1034    /// If `bytes.len()` with [`Self::offset()`] is larger than [`OwnedAlignedBuffer::MAX_CAPACITY`]
1035    #[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            // Doubling the capacity is capped by the largest one `Layout` allows
1043            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        // SAFETY: Sufficient capacity guaranteed above, natural alignment of bytes is 1 for input
1054        // and output, non-overlapping allocations guaranteed by the type system
1055        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    /// Will re-allocate if capacity is not enough to store provided bytes.
1064    ///
1065    /// Returns an error and leaves the buffer unchanged if `self.len() + bytes.len()` with
1066    /// [`Self::offset()`] is larger than [`OwnedAlignedBuffer::MAX_CAPACITY`] or allocation fails.
1067    #[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            // Offset is not larger than the capacity of the allocation, so this doesn't underflow
1074            .filter(|&new_len| new_len <= MAX_CAPACITY - self.offset())
1075            .ok_or(AllocationError::CapacityOverflow)?;
1076
1077        if new_len > self.capacity() {
1078            // Doubling the capacity is capped by the largest one `Layout` allows
1079            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        // SAFETY: Sufficient capacity guaranteed above, natural alignment of bytes is 1 for input
1090        // and output, non-overlapping allocations guaranteed by the type system
1091        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    /// Append zero padding up to the next multiple of `B` bytes from the beginning of the
1103    /// contents, the inverse of [`SharedAlignedBufferReader::read_to_alignment()`].
1104    ///
1105    /// Re-allocates like [`Self::append()`] if capacity is not enough.
1106    #[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        /// Zero padding for the largest alignment
1113        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    /// Capacity from the beginning of the contents
1137    #[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    /// Offset of the contents from the beginning of the data region of the allocation
1144    #[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    /// Alignment of the allocation in bytes.
1151    ///
1152    /// It is not smaller than the alignment of the contents, unless the contents happen to be
1153    /// aligned more strictly than the allocation (see [`Self::try_into_start_align()`] and
1154    /// [`Self::realign()`]). Empty buffer without an allocation reports the alignment it grows
1155    /// into.
1156    #[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    /// Shorten the buffer, keeping the first `len` bytes.
1163    ///
1164    /// Does nothing if `len` is not smaller than the current length.
1165    #[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    /// Move the beginning of the contents to `offset` from the beginning of the data region
1174    /// without moving any bytes, the end of the contents stays where it is.
1175    ///
1176    /// Returns `false` and leaves the buffer unchanged if `offset` is outside of the contents or
1177    /// the contents would not be aligned to `A` anymore. [`Self::capacity()`] is counted from the
1178    /// new beginning.
1179    #[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    /// Clear the contents and convert into a buffer with contents aligned to `B` at the
1187    /// beginning of the data region.
1188    ///
1189    /// The allocation is kept if it is aligned to at least `B` and released otherwise, it never
1190    /// allocates or copies. This is useful for reusing the allocation of a buffer, whose contents
1191    /// are aligned less strictly than the next contents need.
1192    #[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        // SAFETY: Not shared, empty contents fit at any offset
1205        unsafe {
1206            self.inner.move_to_offset(0);
1207        }
1208        // Allocation is aligned to `B` as checked above and contents are at its beginning
1209        OwnedAlignedBuffer::from_inner(self.into_inner())
1210    }
1211
1212    /// Move the contents to `offset` from the beginning of the data region, with at least
1213    /// `capacity` bytes available from there, in an allocation aligned to at least `AA`.
1214    ///
1215    /// Contents are moved within the current allocation when it is large enough and sufficiently
1216    /// aligned, otherwise they are copied into a new allocation once.
1217    ///
1218    /// Returns `false` and leaves the buffer unchanged if `offset` is not a multiple of the
1219    /// alignment of the contents or `offset` with `capacity` is larger than
1220    /// [`OwnedAlignedBuffer::MAX_CAPACITY`].
1221    #[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            // SAFETY: Not shared, contents fit into the data region at a new offset
1249            unsafe {
1250                self.inner.move_to_offset(offset);
1251            }
1252        } else {
1253            // SAFETY: Not shared, a new allocation with enough capacity for the contents
1254            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    /// Convert into a buffer with a different alignment of the contents.
1267    ///
1268    /// Free if the contents are already aligned to `B`. Otherwise, the contents are moved within
1269    /// the current allocation to the closest offset aligned to `B` if possible, even if the
1270    /// allocation itself is aligned less strictly, or copied into a new allocation aligned to `B`
1271    /// once.
1272    #[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            // Moving contents backwards always fits, moving them forward only fits with enough
1285            // capacity
1286            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                // SAFETY: Not shared, contents fit into the data region at a new offset
1296                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                // SAFETY: Not shared, a new allocation with enough capacity for the contents
1306                unsafe {
1307                    self.inner.replace(new);
1308                }
1309            }
1310        }
1311
1312        OwnedAlignedBuffer::from_inner(self.into_inner())
1313    }
1314
1315    /// Set the length of the useful data to a specified value.
1316    ///
1317    /// # Safety
1318    /// There must be `new_len` bytes initialized in the buffer.
1319    #[inline(always)]
1320    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
1321    pub unsafe fn set_len(&mut self, new_len: u32) {
1322        // SAFETY: Guaranteed by method contract
1323        unsafe {
1324            self.inner.set_len(new_len);
1325        }
1326    }
1327}
1328
1329impl<A> OwnedAlignedBuffer<A>
1330where
1331    A: AtLeast<Align16>,
1332{
1333    /// Contents as `u128`s.
1334    ///
1335    /// Only whole `u128`s are included: when the length is not a multiple of `u128` size, the
1336    /// bytes after the last whole `u128` are not.
1337    #[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        // SAFETY: Not null, correctly aligned (contents are aligned to at least `u128`), and the
1342        // first `len` elements are initialized, since they are within `self.len()` bytes, which
1343        // are initialized (a protected invariant of the implementation)
1344        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/// Shared aligned buffer for executor purposes.
1369///
1370/// See [`OwnedAlignedBuffer`] for a version that can be mutated.
1371///
1372/// Contents are aligned to `A`, by default 16 bytes (128 bits), which is the largest alignment
1373/// required by primitive types and by extension any type that implements `TrivialType`/`IoType`.
1374#[derive(Debug)]
1375#[repr(transparent)]
1376pub struct SharedAlignedBuffer<A = Align16>
1377where
1378    A: Alignment,
1379{
1380    /// Empty buffer doesn't hold a reference to an allocation and points to the empty allocation
1381    /// instead, all other buffers hold one reference
1382    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    // Panics on 32-bit targets before the reference counter would wrap around
1403    #[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            // Synchronizes with decrements in other instances, such that their accesses to the
1435            // contents happen before deallocation
1436            fence(Ordering::Acquire);
1437            // SAFETY: Non-empty buffer is backed by an allocation, and this was the last reference
1438            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
1458// SAFETY: Heap-allocated data structure, points to the same memory if moved
1459unsafe impl<A> StableDeref for SharedAlignedBuffer<A> where A: Alignment {}
1460// SAFETY: Inner buffer is exactly the same and points to the same memory after clone
1461unsafe impl<A> CloneStableDeref for SharedAlignedBuffer<A> where A: Alignment {}
1462// SAFETY: Inner buffer is exactly the same and points to the same memory after clone
1463unsafe 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    /// Alignment of the contents in bytes.
1515    ///
1516    /// The allocation can be aligned more strictly, see [`Self::allocation_alignment()`].
1517    pub const ALIGN: u32 = A::ALIGN;
1518
1519    /// Empty buffer that is not backed by an allocation
1520    pub const EMPTY: Self = Self::from_inner(InnerBuffer::EMPTY);
1521
1522    /// Create a new instance from provided bytes.
1523    ///
1524    /// Allocation is aligned to the alignment of the contents, but at least 16 bytes.
1525    ///
1526    /// # Panics
1527    /// If `bytes.len()` is larger than [`OwnedAlignedBuffer::MAX_CAPACITY`]
1528    #[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        // SAFETY: Moved out of `ManuallyDrop` that is never used again
1545        unsafe { (&raw const this.inner).read() }
1546    }
1547
1548    /// Tells the compiler that the contents are aligned to `A`, which it can't see otherwise
1549    #[inline(always)]
1550    fn assume_aligned(&self) {
1551        // SAFETY: Contents are aligned to `A`, which is an invariant of the type
1552        unsafe { hint::assert_unchecked(self.inner.is_aligned_to(align_usize::<A>())) }
1553    }
1554
1555    /// Static reference to an empty buffer
1556    #[inline(always)]
1557    pub const fn empty_ref() -> &'static Self {
1558        // SAFETY: `repr(transparent)` wrapper around `InnerBuffer`, and empty buffer is aligned to
1559        // any supported alignment
1560        unsafe { &*(&raw const EMPTY_INNER_BUFFER).cast::<Self>() }
1561    }
1562
1563    /// Convert into owned buffer.
1564    ///
1565    /// If this is the last reference to the allocation, then allocation will be reused with the
1566    /// same offset of the contents, otherwise contents will be copied into a new allocation with
1567    /// the same alignment.
1568    #[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    /// Whether this is the last reference to the allocation of a non-empty buffer
1581    #[inline(always)]
1582    fn is_last_reference(&self) -> bool {
1583        // Synchronizes with decrements in other instances, such that their accesses to the
1584        // contents happen before modifications through this instance or an owned buffer it is
1585        // converted into
1586        self.inner.strong_count_ref().load(Ordering::Acquire) == 1
1587    }
1588
1589    /// Convert into owned buffer if this is the last reference to the allocation, which is reused
1590    /// with the same offset of the contents.
1591    ///
1592    /// Returns the buffer back if the allocation is still shared.
1593    #[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            // This was the last reference, so owned buffer is not shared
1602            Ok(OwnedAlignedBuffer::from_inner(self.into_inner()))
1603        } else {
1604            Err(self)
1605        }
1606    }
1607
1608    /// Mutable access to the contents if this is the last reference to the allocation, similarly
1609    /// to [`Arc::get_mut()`](alloc::sync::Arc::get_mut).
1610    ///
1611    /// Returns `None` if the allocation is still shared.
1612    #[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            // This is the last reference to the allocation, and it is borrowed mutably
1622            Some(self.inner.as_mut_slice())
1623        } else {
1624            None
1625        }
1626    }
1627
1628    /// Mutable access to the contents, similarly to
1629    /// [`Arc::make_mut()`](alloc::sync::Arc::make_mut).
1630    ///
1631    /// If the allocation is still shared, contents are copied into a new allocation with the same
1632    /// alignment first, see [`Self::into_owned()`].
1633    #[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        // This is the last reference to the allocation (either checked above or just allocated),
1648        // and it is borrowed mutably
1649        self.inner.as_mut_slice()
1650    }
1651
1652    /// Make sure the buffer doesn't keep a larger allocation alive than its contents need.
1653    ///
1654    /// Contents are copied into a new allocation without offset, unless they already cover the
1655    /// whole data region of the allocation. This is useful for buffers that are kept for a long
1656    /// time and may be a part of a much larger allocation, see [`Self::get_slice()`].
1657    ///
1658    /// The new allocation is aligned to the alignment of the contents, but at least 16 bytes,
1659    /// rather than the alignment of the original allocation, which may be much larger than
1660    /// necessary.
1661    #[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    /// Create a new buffer that references a part of the contents of this one without copying
1672    /// them.
1673    ///
1674    /// Returns `None` if `range` is out of bounds. Alignment of the contents is not guaranteed
1675    /// anymore, use [`SharedAlignedBuffer::try_into_start_align()`] if necessary. The new buffer
1676    /// keeps the whole allocation alive, see [`Self::into_standalone()`].
1677    #[inline]
1678    #[must_use = "The slice is dropped otherwise"]
1679    // Panics on 32-bit targets before the reference counter would wrap around
1680    #[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    /// Split into two buffers at `mid` without copying the contents, similarly to
1711    /// [`slice::split_at_checked()`].
1712    ///
1713    /// The first buffer references bytes before `mid` and keeps the alignment of the contents. The
1714    /// second buffer references the rest, whose alignment is not guaranteed anymore, use
1715    /// [`SharedAlignedBuffer::try_into_start_align()`] if necessary. Returns `None` if `mid` is
1716    /// larger than the length. Both buffers keep the whole allocation alive unless they are empty,
1717    /// see [`Self::into_standalone()`].
1718    #[inline]
1719    #[must_use = "Buffers are dropped otherwise"]
1720    // Panics on 32-bit targets before the reference counter would wrap around
1721    #[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    /// Read the contents front to back, see [`SharedAlignedBufferReader`]
1737    #[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    /// Shorten the buffer, keeping the first `len` bytes.
1744    ///
1745    /// Does nothing if `len` is not smaller than the current length. Empty buffer doesn't keep the
1746    /// allocation alive.
1747    #[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    /// Move the beginning of the contents to `offset` from the beginning of the data region
1758    /// without moving any bytes, the end of the contents stays where it is.
1759    ///
1760    /// Returns `false` and leaves the buffer unchanged if `offset` is outside of the contents or
1761    /// the contents would not be aligned to `A` anymore. Other buffers that reference the same
1762    /// allocation are not affected. Empty buffer at the end of the contents doesn't keep the
1763    /// allocation alive, see [`Self::truncate()`].
1764    #[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    /// Convert into a buffer with a weaker alignment of the contents, which is free
1779    #[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    /// Convert into a buffer with a different alignment of the contents, which is free.
1791    ///
1792    /// Returns the buffer back if its contents are not aligned to `B`.
1793    #[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    /// Pointer to the first byte of the contents
1814    #[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    /// Capacity from the beginning of the contents
1834    #[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    /// Offset of the contents from the beginning of the data region of the allocation
1841    #[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    /// Alignment of the allocation in bytes.
1848    ///
1849    /// It is not smaller than the alignment of the contents, unless the contents happen to be
1850    /// aligned more strictly than the allocation (see [`Self::try_into_start_align()`]). Empty
1851    /// buffer without an allocation reports the alignment it grows into.
1852    #[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
1874/// Common interface of [`OwnedAlignedBuffer`] and [`SharedAlignedBuffer`].
1875///
1876/// Contents don't move when the buffer is moved, so a buffer can be moved into an operation that
1877/// accesses its memory, like asynchronous I/O, which then returns it back.
1878pub trait AlignedBuffer:
1879    sealed::Sealed + Deref<Target = [u8]> + StableDeref + fmt::Debug + Send + Sync + 'static
1880{
1881    /// Alignment of the contents
1882    type Alignment: Alignment;
1883
1884    /// Length of the contents
1885    fn len(&self) -> u32;
1886
1887    /// Whether the contents are empty
1888    fn is_empty(&self) -> bool;
1889
1890    /// Offset of the contents from the beginning of the data region of the allocation
1891    fn offset(&self) -> u32;
1892
1893    /// Move the beginning of the contents forward to `offset` without moving any bytes, see
1894    /// [`OwnedAlignedBuffer::set_offset()`]
1895    #[must_use = "Check for invalid offset"]
1896    fn set_offset(&mut self, offset: u32) -> bool;
1897
1898    /// Alignment of the allocation in bytes, see [`OwnedAlignedBuffer::allocation_alignment()`]
1899    fn allocation_alignment(&self) -> u32;
1900
1901    /// Convert into shared buffer, which reuses the allocation
1902    fn into_shared(self) -> SharedAlignedBuffer<Self::Alignment>;
1903}