vortex_vector/binaryview/
scalar.rs

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