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