Skip to main content

vortex_array/array/
view.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::fmt::Debug;
5use std::fmt::Formatter;
6use std::ops::Deref;
7
8use vortex_error::VortexResult;
9
10use crate::ArrayRef;
11use crate::array::Array;
12use crate::array::ArrayId;
13use crate::array::VTable;
14use crate::dtype::DType;
15use crate::stats::StatsSetRef;
16use crate::validity::Validity;
17
18/// A lightweight, `Copy`-able typed view into an [`ArrayRef`].
19pub struct ArrayView<'a, V: VTable> {
20    array: &'a ArrayRef,
21    data: &'a V::ArrayData,
22}
23
24impl<V: VTable> Copy for ArrayView<'_, V> {}
25
26impl<V: VTable> Clone for ArrayView<'_, V> {
27    fn clone(&self) -> Self {
28        *self
29    }
30}
31
32impl<'a, V: VTable> ArrayView<'a, V> {
33    /// # Safety
34    /// Caller must ensure `data` is the `V::ArrayData` stored inside `array`.
35    pub(crate) unsafe fn new_unchecked(array: &'a ArrayRef, data: &'a V::ArrayData) -> Self {
36        debug_assert!(array.is::<V>());
37        Self { array, data }
38    }
39
40    pub fn array(&self) -> &'a ArrayRef {
41        self.array
42    }
43
44    pub fn data(&self) -> &'a V::ArrayData {
45        self.data
46    }
47
48    pub fn slots(&self) -> &'a [Option<ArrayRef>] {
49        self.array.slots()
50    }
51
52    pub fn dtype(&self) -> &DType {
53        self.array.dtype()
54    }
55
56    pub fn len(&self) -> usize {
57        self.array.len()
58    }
59
60    pub fn is_empty(&self) -> bool {
61        self.array.len() == 0
62    }
63
64    pub fn encoding_id(&self) -> ArrayId {
65        self.array.encoding_id()
66    }
67
68    pub fn statistics(&self) -> StatsSetRef<'_> {
69        self.array.statistics()
70    }
71
72    pub fn validity(&self) -> VortexResult<Validity> {
73        self.array.validity()
74    }
75
76    pub fn into_owned(self) -> Array<V> {
77        // SAFETY: we are ourselves type checked as 'V'
78        unsafe { Array::<V>::from_array_ref_unchecked(self.array.clone()) }
79    }
80}
81
82impl<V: VTable> AsRef<ArrayRef> for ArrayView<'_, V> {
83    fn as_ref(&self) -> &ArrayRef {
84        self.array
85    }
86}
87
88impl<V: VTable> Deref for ArrayView<'_, V> {
89    type Target = V::ArrayData;
90
91    fn deref(&self) -> &V::ArrayData {
92        self.data
93    }
94}
95
96impl<V: VTable> Debug for ArrayView<'_, V> {
97    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
98        f.debug_struct("ArrayView")
99            .field("encoding", &self.array.encoding_id())
100            .field("dtype", self.array.dtype())
101            .field("len", &self.array.len())
102            .finish()
103    }
104}