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
use std::sync::Arc;

use vortex_dtype::DType;
use vortex_error::{vortex_bail, VortexError, VortexResult};

use crate::value::ScalarValue;
use crate::Scalar;

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

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

    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 cast(&self, _dtype: &DType) -> VortexResult<Scalar> {
        todo!()
    }
}

impl Scalar {
    pub fn r#struct(dtype: DType, children: Vec<ScalarValue>) -> Self {
        Self {
            dtype,
            value: ScalarValue::List(children.into()),
        }
    }
}

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

    fn try_from(value: &'a Scalar) -> Result<Self, Self::Error> {
        if matches!(value.dtype(), DType::Struct(..)) {
            vortex_bail!("Expected struct scalar, found {}", value.dtype())
        }
        Ok(Self {
            dtype: value.dtype(),
            fields: value.value.as_list()?.cloned(),
        })
    }
}