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::ArraySlots;
8use crate::array::Array;
9use crate::array::ArrayParts;
10use crate::arrays::Constant;
11use crate::scalar::Scalar;
12
13#[derive(Clone, Debug)]
14pub struct ConstantData {
15    pub(super) scalar: Scalar,
16}
17
18impl Display for ConstantData {
19    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
20        write!(f, "scalar: {}", self.scalar)
21    }
22}
23
24impl ConstantData {
25    pub fn new<S>(scalar: S) -> Self
26    where
27        S: Into<Scalar>,
28    {
29        let scalar = scalar.into();
30        Self { scalar }
31    }
32
33    /// Returns the [`Scalar`] value of this constant array.
34    pub fn scalar(&self) -> &Scalar {
35        &self.scalar
36    }
37
38    pub fn into_parts(self) -> Scalar {
39        self.scalar
40    }
41}
42
43impl Array<Constant> {
44    pub fn new<S>(scalar: S, len: usize) -> Self
45    where
46        S: Into<Scalar>,
47    {
48        Self::from_scalar(scalar.into(), len)
49    }
50
51    /// Creates the array from a [`Scalar`].
52    ///
53    /// The generic constructors call this function. It is not generic, so crates that call those
54    /// constructors do not each compile the `Constant` array vtable.
55    fn from_scalar(scalar: Scalar, len: usize) -> Self {
56        let dtype = scalar.dtype().clone();
57        let data = ConstantData::new(scalar);
58        unsafe {
59            Array::from_parts_unchecked(ArrayParts::new(
60                Constant,
61                dtype,
62                len,
63                data,
64                ArraySlots::new(),
65            ))
66        }
67    }
68}