Skip to main content

coip_format/
schema.rs

1use alloc::boxed::Box;
2use alloc::format;
3use alloc::string::String;
4use alloc::vec;
5use alloc::vec::Vec;
6
7use crate::varint::write_string;
8use crate::{Cursor, FormatError};
9
10pub const SCHEMA_VERSION: u16 = 1;
11
12/// Primitive column value types.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
14#[repr(u8)]
15pub enum PType {
16    Bool = 1,
17    U8 = 2,
18    U16 = 3,
19    U32 = 4,
20    U64 = 5,
21    U128 = 6,
22    I32 = 7,
23    I64 = 8,
24    F32 = 9,
25    F64 = 10,
26    Utf8 = 11,
27    Bytes = 12,
28}
29
30impl PType {
31    #[inline]
32    pub fn from_u8(v: u8) -> Result<Self, FormatError> {
33        match v {
34            1 => Ok(Self::Bool),
35            2 => Ok(Self::U8),
36            3 => Ok(Self::U16),
37            4 => Ok(Self::U32),
38            5 => Ok(Self::U64),
39            6 => Ok(Self::U128),
40            7 => Ok(Self::I32),
41            8 => Ok(Self::I64),
42            9 => Ok(Self::F32),
43            10 => Ok(Self::F64),
44            11 => Ok(Self::Utf8),
45            12 => Ok(Self::Bytes),
46            _ => Err(FormatError::InvalidPType(v)),
47        }
48    }
49
50    pub const fn name(self) -> &'static str {
51        match self {
52            Self::Bool => "Bool",
53            Self::U8 => "U8",
54            Self::U16 => "U16",
55            Self::U32 => "U32",
56            Self::U64 => "U64",
57            Self::U128 => "U128",
58            Self::I32 => "I32",
59            Self::I64 => "I64",
60            Self::F32 => "F32",
61            Self::F64 => "F64",
62            Self::Utf8 => "Utf8",
63            Self::Bytes => "Bytes",
64        }
65    }
66
67    /// Fixed byte width for Plain array encoding (`None` for Bool/Utf8/Bytes).
68    pub const fn fixed_byte_width(self) -> Option<usize> {
69        match self {
70            Self::U8 => Some(1),
71            Self::U16 => Some(2),
72            Self::U32 | Self::I32 | Self::F32 => Some(4),
73            Self::U64 | Self::I64 | Self::F64 => Some(8),
74            Self::U128 => Some(16),
75            Self::Bool | Self::Utf8 | Self::Bytes => None,
76        }
77    }
78
79    /// Whether `EncMode::Delta` is supported for this type.
80    pub const fn supports_delta(self) -> bool {
81        matches!(
82            self,
83            Self::U8 | Self::U16 | Self::U32 | Self::U64 | Self::I32 | Self::I64
84        )
85    }
86}
87
88/// Physical integer width for dictionary ID references (`0 = None`, `1..=K -> entry[id - 1]`).
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
90#[repr(u8)]
91pub enum IdWidth {
92    U8 = 1,
93    U16 = 2,
94    U32 = 4,
95}
96
97impl IdWidth {
98    #[inline]
99    pub fn from_u8(v: u8) -> Result<Self, FormatError> {
100        match v {
101            1 => Ok(Self::U8),
102            2 => Ok(Self::U16),
103            4 => Ok(Self::U32),
104            _ => Err(FormatError::InvalidIdWidth(v)),
105        }
106    }
107
108    /// Pick the smallest `IdWidth` that can represent `1..=dict_len` (reserving `0` for `None`).
109    #[inline]
110    pub const fn for_dict_len(dict_len: usize) -> Self {
111        if dict_len <= u8::MAX as usize {
112            Self::U8
113        } else if dict_len <= u16::MAX as usize {
114            Self::U16
115        } else {
116            Self::U32
117        }
118    }
119
120    #[inline]
121    pub const fn as_ptype(self) -> PType {
122        match self {
123            Self::U8 => PType::U8,
124            Self::U16 => PType::U16,
125            Self::U32 => PType::U32,
126        }
127    }
128}
129
130/// Physical storage type of one column inside a `ColumnTable`.
131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
132pub enum PhysicalColKind {
133    Primitive(PType),
134    Dynamic,
135}
136
137/// Complete self-describing Schema stored in Section 2.
138#[derive(Debug, Clone, PartialEq, Eq)]
139pub struct Schema {
140    pub dicts: Vec<DictSchema>,
141    pub root: TableSchema,
142}
143
144impl Schema {
145    pub fn encode(&self) -> Vec<u8> {
146        let mut out = Vec::new();
147        out.extend_from_slice(&SCHEMA_VERSION.to_le_bytes());
148        out.extend_from_slice(&(self.dicts.len() as u16).to_le_bytes());
149        for d in &self.dicts {
150            d.encode(&mut out);
151        }
152        self.root.encode(&mut out);
153        out
154    }
155
156    pub fn decode(buf: &[u8]) -> Result<Self, FormatError> {
157        let mut c = Cursor::new(buf);
158        let version = c.read_u16()?;
159        if version != SCHEMA_VERSION {
160            return Err(FormatError::InvalidSchema(format!(
161                "unsupported schema version {version}"
162            )));
163        }
164        let dict_count = c.read_u16()? as usize;
165        let mut dicts = Vec::with_capacity(dict_count);
166        for _ in 0..dict_count {
167            dicts.push(DictSchema::decode(&mut c)?);
168        }
169        let root = TableSchema::decode(&mut c)?;
170        let schema = Self { dicts, root };
171        schema.validate()?;
172        Ok(schema)
173    }
174
175    /// Validate column indices and dictionary references across the schema.
176    pub fn validate(&self) -> Result<(), FormatError> {
177        let _ = self.root.physical_column_kinds(self.dicts.len())?;
178        for (idx, d) in self.dicts.iter().enumerate() {
179            match &d.kind {
180                DictKind::Flat { .. } => {}
181                DictKind::Struct { table } => {
182                    let _ = table.physical_column_kinds(self.dicts.len())?;
183                }
184                DictKind::List { elem_dict_id, .. } => {
185                    if (*elem_dict_id as usize) >= self.dicts.len() {
186                        return Err(FormatError::InvalidSchema(format!(
187                            "ListDict {idx} references out-of-range elem_dict_id {elem_dict_id}"
188                        )));
189                    }
190                }
191            }
192        }
193        Ok(())
194    }
195}
196
197/// Schema descriptor for one dictionary in Section 9 (`DictTables`).
198#[derive(Debug, Clone, PartialEq, Eq)]
199pub struct DictSchema {
200    pub name: String,
201    pub kind: DictKind,
202}
203
204impl DictSchema {
205    pub fn encode(&self, out: &mut Vec<u8>) {
206        write_string(out, &self.name);
207        match &self.kind {
208            DictKind::Flat {
209                ptype,
210                sorted_front_coded,
211                block_size,
212            } => {
213                out.push(1);
214                out.push(*ptype as u8);
215                out.push(u8::from(*sorted_front_coded));
216                out.extend_from_slice(&block_size.to_le_bytes());
217            }
218            DictKind::Struct { table } => {
219                out.push(2);
220                table.encode(out);
221            }
222            DictKind::List {
223                elem_dict_id,
224                id_width,
225            } => {
226                out.push(3);
227                out.extend_from_slice(&elem_dict_id.to_le_bytes());
228                out.push(*id_width as u8);
229                out.push(0); // reserved flags
230            }
231        }
232    }
233
234    pub fn decode(c: &mut Cursor<'_>) -> Result<Self, FormatError> {
235        let name = c.read_string()?;
236        let kind_tag = c.read_u8()?;
237        let kind = match kind_tag {
238            1 => {
239                let ptype = PType::from_u8(c.read_u8()?)?;
240                let flags = c.read_u8()?;
241                let block_size = c.read_u32()?;
242                DictKind::Flat {
243                    ptype,
244                    sorted_front_coded: (flags & 1) != 0,
245                    block_size,
246                }
247            }
248            2 => {
249                let table = TableSchema::decode(c)?;
250                DictKind::Struct { table }
251            }
252            3 => {
253                let elem_dict_id = c.read_u16()?;
254                let id_width = IdWidth::from_u8(c.read_u8()?)?;
255                let _flags = c.read_u8()?;
256                DictKind::List {
257                    elem_dict_id,
258                    id_width,
259                }
260            }
261            _ => return Err(FormatError::InvalidDictKind(kind_tag)),
262        };
263        Ok(Self { name, kind })
264    }
265}
266
267#[derive(Debug, Clone, PartialEq, Eq)]
268pub enum DictKind {
269    Flat {
270        ptype: PType,
271        sorted_front_coded: bool,
272        block_size: u32,
273    },
274    Struct {
275        table: TableSchema,
276    },
277    List {
278        elem_dict_id: u16,
279        id_width: IdWidth,
280    },
281}
282
283/// Schema of a `ColumnTable` (root `RecordColumns` or a `StructDict`).
284#[derive(Debug, Clone, PartialEq, Eq)]
285pub struct TableSchema {
286    pub column_count: u16,
287    pub root: StructSchema,
288}
289
290impl TableSchema {
291    pub fn encode(&self, out: &mut Vec<u8>) {
292        out.extend_from_slice(&self.column_count.to_le_bytes());
293        self.root.encode(out);
294    }
295
296    pub fn decode(c: &mut Cursor<'_>) -> Result<Self, FormatError> {
297        let column_count = c.read_u16()?;
298        let root = StructSchema::decode(c)?;
299        Ok(Self { column_count, root })
300    }
301
302    /// Resolve and validate the physical column kind for every `col_id` in `0..column_count`.
303    pub fn physical_column_kinds(
304        &self,
305        dict_count: usize,
306    ) -> Result<Vec<PhysicalColKind>, FormatError> {
307        let mut kinds: Vec<Option<PhysicalColKind>> = vec![None; self.column_count as usize];
308        collect_struct_cols(&self.root, dict_count, &mut kinds)?;
309        let mut out = Vec::with_capacity(self.column_count as usize);
310        for (idx, k) in kinds.into_iter().enumerate() {
311            match k {
312                Some(kind) => out.push(kind),
313                None => {
314                    return Err(FormatError::InvalidSchema(format!(
315                        "physical column {idx} is unreferenced in TableSchema"
316                    )));
317                }
318            }
319        }
320        Ok(out)
321    }
322}
323
324fn assign_col(
325    kinds: &mut [Option<PhysicalColKind>],
326    col_id: u16,
327    kind: PhysicalColKind,
328) -> Result<(), FormatError> {
329    let idx = col_id as usize;
330    if idx >= kinds.len() {
331        return Err(FormatError::InvalidSchema(format!(
332            "col_id {col_id} exceeds column_count {}",
333            kinds.len()
334        )));
335    }
336    if kinds[idx].is_some() {
337        return Err(FormatError::InvalidSchema(format!(
338            "duplicate physical col_id {col_id}"
339        )));
340    }
341    kinds[idx] = Some(kind);
342    Ok(())
343}
344
345fn collect_struct_cols(
346    s: &StructSchema,
347    dict_count: usize,
348    kinds: &mut [Option<PhysicalColKind>],
349) -> Result<(), FormatError> {
350    if let Some(c) = s.presence_col {
351        assign_col(kinds, c, PhysicalColKind::Primitive(PType::Bool))?;
352    }
353    for f in &s.fields {
354        collect_col_type(&f.col_type, dict_count, kinds)?;
355    }
356    for g in &s.dict_groups {
357        if (g.dict_id as usize) >= dict_count {
358            return Err(FormatError::InvalidSchema(format!(
359                "DictGroup references out-of-range dict_id {}",
360                g.dict_id
361            )));
362        }
363        assign_col(
364            kinds,
365            g.col_id,
366            PhysicalColKind::Primitive(g.id_width.as_ptype()),
367        )?;
368    }
369    Ok(())
370}
371
372fn collect_col_type(
373    ct: &ColumnType,
374    dict_count: usize,
375    kinds: &mut [Option<PhysicalColKind>],
376) -> Result<(), FormatError> {
377    match ct {
378        ColumnType::Primitive { ptype, col_id, .. } => {
379            assign_col(kinds, *col_id, PhysicalColKind::Primitive(*ptype))
380        }
381        ColumnType::DictRef {
382            dict_id,
383            id_width,
384            col_id,
385            ..
386        } => {
387            if (*dict_id as usize) >= dict_count {
388                return Err(FormatError::InvalidSchema(format!(
389                    "DictRef references out-of-range dict_id {dict_id}"
390                )));
391            }
392            assign_col(
393                kinds,
394                *col_id,
395                PhysicalColKind::Primitive(id_width.as_ptype()),
396            )
397        }
398        ColumnType::Struct(s) => collect_struct_cols(s, dict_count, kinds),
399        ColumnType::ShreddedMap {
400            presence_col,
401            overflow_col,
402            entries,
403            ..
404        } => {
405            if let Some(c) = presence_col {
406                assign_col(kinds, *c, PhysicalColKind::Primitive(PType::Bool))?;
407            }
408            if let Some(c) = overflow_col {
409                assign_col(kinds, *c, PhysicalColKind::Dynamic)?;
410            }
411            for e in entries {
412                collect_col_type(&e.value_type, dict_count, kinds)?;
413            }
414            Ok(())
415        }
416        ColumnType::List {
417            offsets_col,
418            elem_type,
419            ..
420        } => {
421            assign_col(kinds, *offsets_col, PhysicalColKind::Primitive(PType::U32))?;
422            collect_col_type(elem_type, dict_count, kinds)
423        }
424        ColumnType::Dynamic { col_id, .. } => assign_col(kinds, *col_id, PhysicalColKind::Dynamic),
425    }
426}
427
428/// Struct schema (root or nested).
429#[derive(Debug, Clone, PartialEq, Eq)]
430pub struct StructSchema {
431    pub nullable: bool,
432    pub presence_col: Option<u16>,
433    pub fields: Vec<StructField>,
434    pub dict_groups: Vec<DictGroup>,
435}
436
437impl StructSchema {
438    pub fn encode(&self, out: &mut Vec<u8>) {
439        let mut flags = 0u8;
440        if self.nullable {
441            flags |= 0x01;
442        }
443        if self.presence_col.is_some() {
444            flags |= 0x02;
445        }
446        out.push(flags);
447        if let Some(c) = self.presence_col {
448            out.extend_from_slice(&c.to_le_bytes());
449        }
450        out.extend_from_slice(&(self.fields.len() as u16).to_le_bytes());
451        for f in &self.fields {
452            write_string(out, &f.name);
453            f.col_type.encode(out);
454        }
455        out.extend_from_slice(&(self.dict_groups.len() as u16).to_le_bytes());
456        for g in &self.dict_groups {
457            g.encode(out);
458        }
459    }
460
461    pub fn decode(c: &mut Cursor<'_>) -> Result<Self, FormatError> {
462        let flags = c.read_u8()?;
463        let nullable = (flags & 0x01) != 0;
464        let presence_col = if (flags & 0x02) != 0 {
465            Some(c.read_u16()?)
466        } else {
467            None
468        };
469        let field_count = c.read_u16()? as usize;
470        let mut fields = Vec::with_capacity(field_count);
471        for _ in 0..field_count {
472            let name = c.read_string()?;
473            let col_type = ColumnType::decode(c)?;
474            fields.push(StructField { name, col_type });
475        }
476        let dg_count = c.read_u16()? as usize;
477        let mut dict_groups = Vec::with_capacity(dg_count);
478        for _ in 0..dg_count {
479            dict_groups.push(DictGroup::decode(c)?);
480        }
481        Ok(Self {
482            nullable,
483            presence_col,
484            fields,
485            dict_groups,
486        })
487    }
488}
489
490#[derive(Debug, Clone, PartialEq, Eq)]
491pub struct StructField {
492    pub name: String,
493    pub col_type: ColumnType,
494}
495
496#[derive(Debug, Clone, PartialEq, Eq)]
497pub struct DictGroup {
498    pub dict_id: u16,
499    pub id_width: IdWidth,
500    pub col_id: u16,
501    pub field_names: Vec<String>,
502}
503
504impl DictGroup {
505    pub fn encode(&self, out: &mut Vec<u8>) {
506        out.extend_from_slice(&self.dict_id.to_le_bytes());
507        out.push(self.id_width as u8);
508        out.extend_from_slice(&self.col_id.to_le_bytes());
509        out.extend_from_slice(&(self.field_names.len() as u16).to_le_bytes());
510        for name in &self.field_names {
511            write_string(out, name);
512        }
513    }
514
515    pub fn decode(c: &mut Cursor<'_>) -> Result<Self, FormatError> {
516        let dict_id = c.read_u16()?;
517        let id_width = IdWidth::from_u8(c.read_u8()?)?;
518        let col_id = c.read_u16()?;
519        let count = c.read_u16()? as usize;
520        let mut field_names = Vec::with_capacity(count);
521        for _ in 0..count {
522            field_names.push(c.read_string()?);
523        }
524        Ok(Self {
525            dict_id,
526            id_width,
527            col_id,
528            field_names,
529        })
530    }
531}
532
533#[derive(Debug, Clone, PartialEq, Eq)]
534pub struct ShreddedMapEntry {
535    pub key: String,
536    pub value_type: ColumnType,
537}
538
539/// The 6 orthogonal column primitives in COI Schema v1.0.
540#[derive(Debug, Clone, PartialEq, Eq)]
541pub enum ColumnType {
542    Primitive {
543        ptype: PType,
544        nullable: bool,
545        col_id: u16,
546    },
547    DictRef {
548        dict_id: u16,
549        id_width: IdWidth,
550        nullable: bool,
551        col_id: u16,
552    },
553    Struct(StructSchema),
554    ShreddedMap {
555        nullable: bool,
556        presence_col: Option<u16>,
557        overflow_col: Option<u16>,
558        entries: Vec<ShreddedMapEntry>,
559    },
560    List {
561        nullable: bool,
562        offsets_col: u16,
563        elem_type: Box<ColumnType>,
564    },
565    Dynamic {
566        nullable: bool,
567        col_id: u16,
568    },
569}
570
571impl ColumnType {
572    pub fn encode(&self, out: &mut Vec<u8>) {
573        match self {
574            Self::Primitive {
575                ptype,
576                nullable,
577                col_id,
578            } => {
579                out.push(1);
580                out.push(*ptype as u8);
581                out.push(u8::from(*nullable));
582                out.extend_from_slice(&col_id.to_le_bytes());
583            }
584            Self::DictRef {
585                dict_id,
586                id_width,
587                nullable,
588                col_id,
589            } => {
590                out.push(2);
591                out.extend_from_slice(&dict_id.to_le_bytes());
592                out.push(*id_width as u8);
593                out.push(u8::from(*nullable));
594                out.extend_from_slice(&col_id.to_le_bytes());
595            }
596            Self::Struct(s) => {
597                out.push(3);
598                s.encode(out);
599            }
600            Self::ShreddedMap {
601                nullable,
602                presence_col,
603                overflow_col,
604                entries,
605            } => {
606                out.push(4);
607                let mut flags = 0u8;
608                if *nullable {
609                    flags |= 0x01;
610                }
611                if presence_col.is_some() {
612                    flags |= 0x02;
613                }
614                if overflow_col.is_some() {
615                    flags |= 0x04;
616                }
617                out.push(flags);
618                if let Some(c) = presence_col {
619                    out.extend_from_slice(&c.to_le_bytes());
620                }
621                if let Some(c) = overflow_col {
622                    out.extend_from_slice(&c.to_le_bytes());
623                }
624                out.extend_from_slice(&(entries.len() as u16).to_le_bytes());
625                for e in entries {
626                    write_string(out, &e.key);
627                    e.value_type.encode(out);
628                }
629            }
630            Self::List {
631                nullable,
632                offsets_col,
633                elem_type,
634            } => {
635                out.push(5);
636                out.push(u8::from(*nullable));
637                out.extend_from_slice(&offsets_col.to_le_bytes());
638                elem_type.encode(out);
639            }
640            Self::Dynamic { nullable, col_id } => {
641                out.push(6);
642                out.push(u8::from(*nullable));
643                out.extend_from_slice(&col_id.to_le_bytes());
644            }
645        }
646    }
647
648    pub fn decode(c: &mut Cursor<'_>) -> Result<Self, FormatError> {
649        let tag = c.read_u8()?;
650        match tag {
651            1 => Ok(Self::Primitive {
652                ptype: PType::from_u8(c.read_u8()?)?,
653                nullable: c.read_u8()? != 0,
654                col_id: c.read_u16()?,
655            }),
656            2 => Ok(Self::DictRef {
657                dict_id: c.read_u16()?,
658                id_width: IdWidth::from_u8(c.read_u8()?)?,
659                nullable: c.read_u8()? != 0,
660                col_id: c.read_u16()?,
661            }),
662            3 => Ok(Self::Struct(StructSchema::decode(c)?)),
663            4 => {
664                let flags = c.read_u8()?;
665                let nullable = (flags & 0x01) != 0;
666                let presence_col = if (flags & 0x02) != 0 {
667                    Some(c.read_u16()?)
668                } else {
669                    None
670                };
671                let overflow_col = if (flags & 0x04) != 0 {
672                    Some(c.read_u16()?)
673                } else {
674                    None
675                };
676                let count = c.read_u16()? as usize;
677                let mut entries = Vec::with_capacity(count);
678                for _ in 0..count {
679                    let key = c.read_string()?;
680                    let value_type = ColumnType::decode(c)?;
681                    entries.push(ShreddedMapEntry { key, value_type });
682                }
683                Ok(Self::ShreddedMap {
684                    nullable,
685                    presence_col,
686                    overflow_col,
687                    entries,
688                })
689            }
690            5 => {
691                let nullable = c.read_u8()? != 0;
692                let offsets_col = c.read_u16()?;
693                let elem_type = Box::new(ColumnType::decode(c)?);
694                Ok(Self::List {
695                    nullable,
696                    offsets_col,
697                    elem_type,
698                })
699            }
700            6 => Ok(Self::Dynamic {
701                nullable: c.read_u8()? != 0,
702                col_id: c.read_u16()?,
703            }),
704            _ => Err(FormatError::InvalidColumnTag(tag)),
705        }
706    }
707}