vortex_buffer/bytes.rs
1use bytes::Buf;
2use vortex_error::VortexExpect;
3
4use crate::{Alignment, ByteBuffer, ConstBuffer, ConstByteBuffer};
5
6/// An extension to the [`Buf`] trait that provides a function `copy_to_aligned` similar to
7/// `copy_to_bytes` that allows for zero-copy aligned reads where possible.
8pub trait AlignedBuf: Buf {
9 /// Copy the next `len` bytes from the buffer into a new buffer with the given alignment.
10 /// This will be zero-copy wherever possible.
11 ///
12 /// The [`Buf`] trait has a specialized `copy_to_bytes` function that allows the implementation
13 /// of `Buf` for `Bytes` and `BytesMut` to return bytes with zero-copy.
14 ///
15 /// This function provides similar functionality for `ByteBuffer`.
16 ///
17 /// TODO(ngates): what should this do the alignment of the current buffer? We have to advance
18 /// it by len..
19 fn copy_to_aligned(&mut self, len: usize, alignment: Alignment) -> ByteBuffer {
20 // The default implementation uses copy_to_bytes, and then tries to align.
21 // When the underlying `copy_to_bytes` is zero-copy, this may perform one copy to align
22 // the bytes. When the underlying `copy_to_bytes` is not zero-copy, this may perform two
23 // copies.
24 //
25 // The only way to fix this would be to invert the implementation so `copy_to_bytes`
26 // invokes `copy_to_aligned` with an alignment of 1. But we cannot override this in the
27 // default trait.
28 //
29 // In practice, we tend to only call this function on `ByteBuffer: AlignedBuf`, and
30 // therefore we have a maximum of one copy, so I'm not too worried about it.
31 ByteBuffer::from(self.copy_to_bytes(len)).aligned(alignment)
32 }
33
34 /// See [`AlignedBuf::copy_to_aligned`].
35 fn copy_to_const_aligned<const A: usize>(&mut self, len: usize) -> ConstByteBuffer<A> {
36 // The default implementation uses copy_to_bytes, and then returns a ByteBuffer with
37 // alignment of 1. This will be zero-copy if the underlying `copy_to_bytes` is zero-copy.
38 ConstBuffer::try_from(self.copy_to_aligned(len, Alignment::new(A)))
39 .vortex_expect("we just aligned the buffer")
40 }
41}
42
43impl<B: Buf> AlignedBuf for B {}