Skip to main content

vortex_buffer/
const.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::ops::Deref;
5
6use vortex_error::VortexError;
7use vortex_error::vortex_bail;
8
9use crate::Alignment;
10use crate::Buffer;
11
12/// A buffer of items of `T` with a compile-time alignment.
13#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Hash)]
14pub struct ConstBuffer<T, const A: usize>(Buffer<T>);
15
16impl<T, const A: usize> ConstBuffer<T, A> {
17    /// Returns the alignment of the buffer.
18    pub const fn alignment() -> Alignment {
19        Alignment::new(A)
20    }
21
22    /// Align the given buffer (possibly with a copy) and return a new `ConstBuffer`.
23    pub fn align_from<B: Into<Buffer<T>>>(buf: B) -> Self {
24        Self(buf.into().aligned(Self::alignment()))
25    }
26
27    /// Create a new [`ConstBuffer`] with a copy from the provided slice.
28    pub fn copy_from<B: AsRef<[T]>>(buf: B) -> Self {
29        Self(Buffer::<T>::copy_from_aligned(buf, Self::alignment()))
30    }
31
32    /// Returns a slice over the buffer of elements of type T.
33    #[allow(clippy::inline_always)]
34    #[inline(always)]
35    pub fn as_slice(&self) -> &[T] {
36        self.0.as_slice()
37    }
38
39    /// Unwrap the inner buffer.
40    pub fn inner(&self) -> &Buffer<T> {
41        &self.0
42    }
43
44    /// Unwrap the inner buffer.
45    pub fn into_inner(self) -> Buffer<T> {
46        self.0
47    }
48}
49
50impl<T, const A: usize> TryFrom<Buffer<T>> for ConstBuffer<T, A> {
51    type Error = VortexError;
52
53    fn try_from(value: Buffer<T>) -> Result<Self, Self::Error> {
54        if !value.alignment().is_aligned_to(Alignment::new(A)) {
55            vortex_bail!(
56                "Cannot convert buffer with alignment {} to buffer with alignment {}",
57                value.alignment(),
58                A
59            );
60        }
61        Ok(Self(value))
62    }
63}
64
65impl<T, const A: usize> AsRef<Buffer<T>> for ConstBuffer<T, A> {
66    fn as_ref(&self) -> &Buffer<T> {
67        &self.0
68    }
69}
70
71impl<T, const A: usize> Deref for ConstBuffer<T, A> {
72    type Target = [T];
73
74    fn deref(&self) -> &Self::Target {
75        self.0.as_slice()
76    }
77}