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
use vortex_dtype::field::Field;
use vortex_dtype::DType;
use vortex_error::{vortex_bail, vortex_err, VortexResult};

use self::projection::Projection;

pub mod projection;

#[derive(Clone, Debug)]
pub struct Schema(pub(crate) DType);

impl Schema {
    pub fn new(schema_dtype: DType) -> Self {
        Self(schema_dtype)
    }

    pub fn project(&self, projection: Projection) -> VortexResult<Self> {
        match projection {
            Projection::All => Ok(self.clone()),
            Projection::Flat(indices) => {
                let DType::Struct(s, n) = &self.0 else {
                    vortex_bail!("Can't project non struct types")
                };
                s.project(indices.as_ref())
                    .map(|p| Self(DType::Struct(p, *n)))
            }
        }
    }

    pub fn dtype(&self) -> &DType {
        &self.0
    }

    pub fn field_type(&self, field: &Field) -> VortexResult<DType> {
        let DType::Struct(s, _) = &self.0 else {
            vortex_bail!("Can't project non struct types")
        };

        let idx = match field {
            Field::Name(name) => s.find_name(name),
            Field::Index(i) => Some(*i),
        };

        idx.and_then(|idx| s.dtypes().get(idx).cloned())
            .ok_or_else(|| vortex_err!("Couldn't find struct by {field}"))
    }
}

impl From<Schema> for DType {
    fn from(value: Schema) -> Self {
        value.0
    }
}