1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
use std::collections::HashMap;

use serde::{Deserialize, Serialize};
use vortex_error::VortexResult;
use vortex_scalar::Scalar;

use crate::stats::{Stat, StatsSet};
use crate::validity::{ArrayValidity, LogicalValidity};
use crate::visitor::{AcceptArrayVisitor, ArrayVisitor};
use crate::{impl_encoding, ArrayDef, ArrayTrait};

mod canonical;
mod compute;
mod stats;
mod variants;

impl_encoding!("vortex.constant", 10u16, Constant);

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConstantMetadata {
    scalar: Scalar,
    length: usize,
}

impl ConstantArray {
    pub fn new<S>(scalar: S, length: usize) -> Self
    where
        S: Into<Scalar>,
    {
        let scalar = scalar.into();
        // TODO(aduffy): add stats for bools, ideally there should be a
        //  StatsSet::constant(Scalar) constructor that does this for us, like StatsSet::nulls.
        let stats = StatsSet::from(HashMap::from([
            (Stat::Max, scalar.clone()),
            (Stat::Min, scalar.clone()),
            (Stat::IsConstant, true.into()),
            (Stat::IsSorted, true.into()),
            (Stat::RunCount, 1.into()),
        ]));
        Self::try_from_parts(
            scalar.dtype().clone(),
            length,
            ConstantMetadata { scalar, length },
            [].into(),
            stats,
        )
        .unwrap()
    }

    pub fn scalar(&self) -> &Scalar {
        &self.metadata().scalar
    }
}

impl ArrayTrait for ConstantArray {}

impl ArrayValidity for ConstantArray {
    fn is_valid(&self, _index: usize) -> bool {
        match self.metadata().scalar.dtype().is_nullable() {
            true => !self.scalar().is_null(),
            false => true,
        }
    }

    fn logical_validity(&self) -> LogicalValidity {
        match self.scalar().is_null() {
            true => LogicalValidity::AllInvalid(self.len()),
            false => LogicalValidity::AllValid(self.len()),
        }
    }
}

impl AcceptArrayVisitor for ConstantArray {
    fn accept(&self, _visitor: &mut dyn ArrayVisitor) -> VortexResult<()> {
        Ok(())
    }
}