Skip to main content

vortex_array/arrays/constant/
array.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::fmt::Display;
5use std::fmt::Formatter;
6
7use crate::array::Array;
8use crate::array::ArrayParts;
9use crate::arrays::Constant;
10use crate::scalar::Scalar;
11
12#[derive(Clone, Debug)]
13pub struct ConstantData {
14    pub(super) scalar: Scalar,
15}
16
17impl Display for ConstantData {
18    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
19        write!(f, "scalar: {}", self.scalar)
20    }
21}
22
23impl ConstantData {
24    pub fn new<S>(scalar: S) -> Self
25    where
26        S: Into<Scalar>,
27    {
28        let scalar = scalar.into();
29        Self { scalar }
30    }
31
32    /// Returns the [`Scalar`] value of this constant array.
33    pub fn scalar(&self) -> &Scalar {
34        &self.scalar
35    }
36
37    pub fn into_parts(self) -> Scalar {
38        self.scalar
39    }
40}
41
42impl Array<Constant> {
43    pub fn new<S>(scalar: S, len: usize) -> Self
44    where
45        S: Into<Scalar>,
46    {
47        let scalar = scalar.into();
48        let dtype = scalar.dtype().clone();
49        let data = ConstantData::new(scalar);
50        unsafe { Array::from_parts_unchecked(ArrayParts::new(Constant, dtype, len, data)) }
51    }
52}