swap_buffer_queue/write/
vec.rs

1use alloc::boxed::Box;
2use core::ops::Range;
3
4use crate::{
5    buffer::{Buffer, InsertIntoBuffer, Resize},
6    loom::{cell::Cell, LoomUnsafeCell},
7    write::{BytesSlice, WriteBytesSlice},
8};
9
10/// A bytes buffer with a `HEADER_SIZE`-bytes header and a `TRAILER_SIZE`-bytes trailer.
11#[derive(Default)]
12pub struct WriteVecBuffer<const HEADER_SIZE: usize = 0, const TRAILER_SIZE: usize = 0>(
13    Box<[Cell<u8>]>,
14);
15
16// SAFETY: Buffer values are `Copy` and already initialized
17unsafe impl<const HEADER_SIZE: usize, const TRAILER_SIZE: usize> Buffer
18    for WriteVecBuffer<HEADER_SIZE, TRAILER_SIZE>
19{
20    type Slice<'a> = BytesSlice<'a, HEADER_SIZE, TRAILER_SIZE>;
21
22    #[inline]
23    fn capacity(&self) -> usize {
24        self.0.len().saturating_sub(HEADER_SIZE + TRAILER_SIZE)
25    }
26
27    #[inline]
28    unsafe fn slice(&mut self, range: Range<usize>) -> Self::Slice<'_> {
29        // SAFETY: [Cell<u8>] has the same layout as [u8]
30        BytesSlice::new(unsafe {
31            &mut *(&mut self.0[range.start..HEADER_SIZE + range.end + TRAILER_SIZE] as *mut _
32                as *mut [u8])
33        })
34    }
35
36    #[inline]
37    unsafe fn clear(&mut self, _range: Range<usize>) {}
38}
39
40// SAFETY: Buffer values are `Copy` and already initialized
41unsafe impl<T, const HEADER_SIZE: usize, const TRAILER_SIZE: usize>
42    InsertIntoBuffer<WriteVecBuffer<HEADER_SIZE, TRAILER_SIZE>> for T
43where
44    T: WriteBytesSlice,
45{
46    #[inline]
47    fn size(&self) -> usize {
48        WriteBytesSlice::size(self)
49    }
50
51    #[inline]
52    unsafe fn insert_into(self, buffer: &WriteVecBuffer<HEADER_SIZE, TRAILER_SIZE>, index: usize) {
53        let slice =
54            &buffer.0[HEADER_SIZE + index..HEADER_SIZE + index + WriteBytesSlice::size(&self)];
55        // SAFETY: [Cell<u8>] has the same layout as UnsafeCell<[u8]>
56        unsafe {
57            (*(slice as *const _ as *const LoomUnsafeCell<[u8]>)).with_mut(|s| self.write(&mut *s));
58        };
59    }
60}
61
62impl<const HEADER_SIZE: usize, const TRAILER_SIZE: usize> Resize
63    for WriteVecBuffer<HEADER_SIZE, TRAILER_SIZE>
64{
65    fn resize(&mut self, capacity: usize) {
66        let full_capacity = HEADER_SIZE + capacity + TRAILER_SIZE;
67        let buffer = alloc::vec![0u8; full_capacity].into_boxed_slice();
68        // SAFETY: [Cell<u8>] has the same layout as [u8]
69        self.0 = unsafe { Box::from_raw(Box::into_raw(buffer) as *mut _) };
70    }
71}