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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
use std::ops::Deref;
use std::sync::Arc;

use itertools::Itertools;
use vortex_dtype::field::Field;
use vortex_dtype::{DType, StructDType};
use vortex_error::{
    vortex_bail, vortex_err, vortex_panic, VortexError, VortexExpect, VortexResult,
};

use crate::value::ScalarValue;
use crate::{InnerScalarValue, Scalar};

pub struct StructScalar<'a> {
    dtype: &'a DType,
    fields: Option<&'a Arc<[ScalarValue]>>,
}

impl<'a> StructScalar<'a> {
    pub(crate) fn try_new(dtype: &'a DType, value: &'a ScalarValue) -> VortexResult<Self> {
        if !matches!(dtype, DType::Struct(..)) {
            vortex_bail!("Expected struct scalar, found {}", dtype)
        }
        Ok(Self {
            dtype,
            fields: value.as_list()?,
        })
    }

    #[inline]
    pub fn dtype(&self) -> &'a DType {
        self.dtype
    }

    #[inline]
    pub fn struct_dtype(&self) -> &'a StructDType {
        let DType::Struct(sdtype, ..) = self.dtype else {
            vortex_panic!("StructScalar always has struct dtype");
        };
        sdtype
    }

    pub fn is_null(&self) -> bool {
        self.fields.is_none()
    }

    pub fn field_by_idx(&self, idx: usize) -> Option<Scalar> {
        let DType::Struct(st, _) = self.dtype() else {
            unreachable!()
        };

        self.fields
            .as_ref()
            .and_then(|fields| fields.get(idx))
            .map(|field| Scalar {
                dtype: st.dtypes()[idx].clone(),
                value: field.clone(),
            })
    }

    pub fn field(&self, name: &str) -> Option<Scalar> {
        let DType::Struct(st, _) = self.dtype() else {
            unreachable!()
        };
        st.find_name(name).and_then(|idx| self.field_by_idx(idx))
    }

    pub fn fields(&self) -> Option<Vec<Scalar>> {
        let fields = self.fields?;

        Some(
            (0..fields.len())
                .map(|index| self.field_by_idx(index).vortex_expect("struct is non-null"))
                .collect(),
        )
    }

    pub(crate) fn field_values(&self) -> Option<&[ScalarValue]> {
        self.fields.map(Arc::deref)
    }

    pub fn cast(&self, dtype: &DType) -> VortexResult<Scalar> {
        let DType::Struct(st, _) = dtype else {
            vortex_bail!("Can only cast struct to another struct")
        };
        let DType::Struct(own_st, _) = self.dtype() else {
            unreachable!()
        };

        if st.dtypes().len() != own_st.dtypes().len() {
            vortex_bail!(
                "Cannot cast between structs with different number of fields: {} and {}",
                own_st.dtypes().len(),
                st.dtypes().len()
            );
        }

        if let Some(fs) = self.field_values() {
            let fields = fs
                .iter()
                .enumerate()
                .map(|(i, f)| {
                    Scalar {
                        dtype: own_st.dtypes()[i].clone(),
                        value: f.clone(),
                    }
                    .cast(&st.dtypes()[i])
                    .map(|s| s.value)
                })
                .collect::<VortexResult<Vec<_>>>()?;
            Ok(Scalar {
                dtype: dtype.clone(),
                value: ScalarValue(InnerScalarValue::List(fields.into())),
            })
        } else {
            Ok(Scalar::null(dtype.clone()))
        }
    }

    pub fn project(&self, projection: &[Field]) -> VortexResult<Scalar> {
        let struct_dtype = self
            .dtype
            .as_struct()
            .ok_or_else(|| vortex_err!("Not a struct dtype"))?;
        let projected_dtype = struct_dtype.project(projection)?;
        let new_fields = if let Some(fs) = self.field_values() {
            ScalarValue(InnerScalarValue::List(
                projection
                    .iter()
                    .map(|p| match p {
                        Field::Name(n) => struct_dtype
                            .find_name(n)
                            .vortex_expect("DType has been successfully projected already"),
                        Field::Index(i) => *i,
                    })
                    .map(|i| fs[i].clone())
                    .collect(),
            ))
        } else {
            ScalarValue(InnerScalarValue::Null)
        };
        Ok(Scalar::new(
            DType::Struct(projected_dtype, self.dtype().nullability()),
            new_fields,
        ))
    }
}

impl Scalar {
    pub fn struct_(dtype: DType, children: Vec<Scalar>) -> Self {
        Self {
            dtype,
            value: ScalarValue(InnerScalarValue::List(
                children
                    .into_iter()
                    .map(|x| x.into_value())
                    .collect_vec()
                    .into(),
            )),
        }
    }
}

impl<'a> TryFrom<&'a Scalar> for StructScalar<'a> {
    type Error = VortexError;

    fn try_from(value: &'a Scalar) -> Result<Self, Self::Error> {
        Self::try_new(value.dtype(), &value.value)
    }
}