1use std::ops::Deref;
5
6use vortex_error::VortexError;
7use vortex_error::vortex_bail;
8
9use crate::Alignment;
10use crate::Buffer;
11
12#[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 pub const fn alignment() -> Alignment {
19 Alignment::new(A)
20 }
21
22 pub fn align_from<B: Into<Buffer<T>>>(buf: B) -> Self {
24 Self(buf.into().aligned(Self::alignment()))
25 }
26
27 pub fn copy_from<B: AsRef<[T]>>(buf: B) -> Self {
29 Self(Buffer::<T>::copy_from_aligned(buf, Self::alignment()))
30 }
31
32 #[allow(clippy::inline_always)]
34 #[inline(always)]
35 pub fn as_slice(&self) -> &[T] {
36 self.0.as_slice()
37 }
38
39 pub fn inner(&self) -> &Buffer<T> {
41 &self.0
42 }
43
44 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}