vortex_vector/binaryview/
scalar.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use crate::Scalar;
5use crate::ScalarOps;
6use crate::VectorMutOps;
7use crate::binaryview::BinaryType;
8use crate::binaryview::BinaryViewType;
9use crate::binaryview::BinaryViewTypeUpcast;
10use crate::binaryview::BinaryViewVectorMut;
11use crate::binaryview::StringType;
12
13/// A scalar value for types that implement [`BinaryViewType`].
14#[derive(Clone, Debug)]
15pub struct BinaryViewScalar<T: BinaryViewType>(Option<T::Scalar>);
16
17impl<T: BinaryViewType> BinaryViewScalar<T> {
18    /// Creates a new binary view scalar with the given value.
19    pub fn new(value: Option<T::Scalar>) -> Self {
20        Self(value)
21    }
22}
23
24impl<T: BinaryViewType> BinaryViewScalar<T> {
25    /// Returns the scalar value as [`BinaryViewType::Scalar`], or `None` if the scalar is null.
26    pub fn value(&self) -> Option<&T::Scalar> {
27        self.0.as_ref()
28    }
29}
30
31impl<T: BinaryViewType> ScalarOps for BinaryViewScalar<T> {
32    fn is_valid(&self) -> bool {
33        self.0.is_some()
34    }
35
36    fn mask_validity(&mut self, mask: bool) {
37        if !mask {
38            self.0 = None;
39        }
40    }
41
42    fn repeat(&self, n: usize) -> crate::VectorMut {
43        let mut vec = BinaryViewVectorMut::<T>::with_capacity(n);
44        match self.value() {
45            None => vec.append_nulls(n),
46            Some(buf) => vec.append_owned_values(buf.clone(), n),
47        }
48        vec.into()
49    }
50}
51
52impl BinaryViewTypeUpcast for Scalar {
53    type Input<T: BinaryViewType> = BinaryViewScalar<T>;
54
55    fn from_binary(input: Self::Input<BinaryType>) -> Self {
56        Scalar::Binary(input)
57    }
58
59    fn from_string(input: Self::Input<StringType>) -> Self {
60        Scalar::String(input)
61    }
62}
63
64impl<T: BinaryViewType> From<BinaryViewScalar<T>> for Scalar {
65    fn from(val: BinaryViewScalar<T>) -> Self {
66        T::upcast(val)
67    }
68}