coip-format 0.1.0

Core binary format definitions, schema, varint, CRC32C, and wire codecs for COI (.coi) columnar IP databases
Documentation
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
use alloc::boxed::Box;
use alloc::format;
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;

use crate::varint::write_string;
use crate::{Cursor, FormatError};

pub const SCHEMA_VERSION: u16 = 1;

/// Primitive column value types.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum PType {
    Bool = 1,
    U8 = 2,
    U16 = 3,
    U32 = 4,
    U64 = 5,
    U128 = 6,
    I32 = 7,
    I64 = 8,
    F32 = 9,
    F64 = 10,
    Utf8 = 11,
    Bytes = 12,
}

impl PType {
    #[inline]
    pub fn from_u8(v: u8) -> Result<Self, FormatError> {
        match v {
            1 => Ok(Self::Bool),
            2 => Ok(Self::U8),
            3 => Ok(Self::U16),
            4 => Ok(Self::U32),
            5 => Ok(Self::U64),
            6 => Ok(Self::U128),
            7 => Ok(Self::I32),
            8 => Ok(Self::I64),
            9 => Ok(Self::F32),
            10 => Ok(Self::F64),
            11 => Ok(Self::Utf8),
            12 => Ok(Self::Bytes),
            _ => Err(FormatError::InvalidPType(v)),
        }
    }

    pub const fn name(self) -> &'static str {
        match self {
            Self::Bool => "Bool",
            Self::U8 => "U8",
            Self::U16 => "U16",
            Self::U32 => "U32",
            Self::U64 => "U64",
            Self::U128 => "U128",
            Self::I32 => "I32",
            Self::I64 => "I64",
            Self::F32 => "F32",
            Self::F64 => "F64",
            Self::Utf8 => "Utf8",
            Self::Bytes => "Bytes",
        }
    }

    /// Fixed byte width for Plain array encoding (`None` for Bool/Utf8/Bytes).
    pub const fn fixed_byte_width(self) -> Option<usize> {
        match self {
            Self::U8 => Some(1),
            Self::U16 => Some(2),
            Self::U32 | Self::I32 | Self::F32 => Some(4),
            Self::U64 | Self::I64 | Self::F64 => Some(8),
            Self::U128 => Some(16),
            Self::Bool | Self::Utf8 | Self::Bytes => None,
        }
    }

    /// Whether `EncMode::Delta` is supported for this type.
    pub const fn supports_delta(self) -> bool {
        matches!(
            self,
            Self::U8 | Self::U16 | Self::U32 | Self::U64 | Self::I32 | Self::I64
        )
    }
}

/// Physical integer width for dictionary ID references (`0 = None`, `1..=K -> entry[id - 1]`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum IdWidth {
    U8 = 1,
    U16 = 2,
    U32 = 4,
}

impl IdWidth {
    #[inline]
    pub fn from_u8(v: u8) -> Result<Self, FormatError> {
        match v {
            1 => Ok(Self::U8),
            2 => Ok(Self::U16),
            4 => Ok(Self::U32),
            _ => Err(FormatError::InvalidIdWidth(v)),
        }
    }

    /// Pick the smallest `IdWidth` that can represent `1..=dict_len` (reserving `0` for `None`).
    #[inline]
    pub const fn for_dict_len(dict_len: usize) -> Self {
        if dict_len <= u8::MAX as usize {
            Self::U8
        } else if dict_len <= u16::MAX as usize {
            Self::U16
        } else {
            Self::U32
        }
    }

    #[inline]
    pub const fn as_ptype(self) -> PType {
        match self {
            Self::U8 => PType::U8,
            Self::U16 => PType::U16,
            Self::U32 => PType::U32,
        }
    }
}

/// Physical storage type of one column inside a `ColumnTable`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PhysicalColKind {
    Primitive(PType),
    Dynamic,
}

/// Complete self-describing Schema stored in Section 2.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Schema {
    pub dicts: Vec<DictSchema>,
    pub root: TableSchema,
}

impl Schema {
    pub fn encode(&self) -> Vec<u8> {
        let mut out = Vec::new();
        out.extend_from_slice(&SCHEMA_VERSION.to_le_bytes());
        out.extend_from_slice(&(self.dicts.len() as u16).to_le_bytes());
        for d in &self.dicts {
            d.encode(&mut out);
        }
        self.root.encode(&mut out);
        out
    }

    pub fn decode(buf: &[u8]) -> Result<Self, FormatError> {
        let mut c = Cursor::new(buf);
        let version = c.read_u16()?;
        if version != SCHEMA_VERSION {
            return Err(FormatError::InvalidSchema(format!(
                "unsupported schema version {version}"
            )));
        }
        let dict_count = c.read_u16()? as usize;
        let mut dicts = Vec::with_capacity(dict_count);
        for _ in 0..dict_count {
            dicts.push(DictSchema::decode(&mut c)?);
        }
        let root = TableSchema::decode(&mut c)?;
        let schema = Self { dicts, root };
        schema.validate()?;
        Ok(schema)
    }

    /// Validate column indices and dictionary references across the schema.
    pub fn validate(&self) -> Result<(), FormatError> {
        let _ = self.root.physical_column_kinds(self.dicts.len())?;
        for (idx, d) in self.dicts.iter().enumerate() {
            match &d.kind {
                DictKind::Flat { .. } => {}
                DictKind::Struct { table } => {
                    let _ = table.physical_column_kinds(self.dicts.len())?;
                }
                DictKind::List { elem_dict_id, .. } => {
                    if (*elem_dict_id as usize) >= self.dicts.len() {
                        return Err(FormatError::InvalidSchema(format!(
                            "ListDict {idx} references out-of-range elem_dict_id {elem_dict_id}"
                        )));
                    }
                }
            }
        }
        Ok(())
    }
}

/// Schema descriptor for one dictionary in Section 9 (`DictTables`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DictSchema {
    pub name: String,
    pub kind: DictKind,
}

impl DictSchema {
    pub fn encode(&self, out: &mut Vec<u8>) {
        write_string(out, &self.name);
        match &self.kind {
            DictKind::Flat {
                ptype,
                sorted_front_coded,
                block_size,
            } => {
                out.push(1);
                out.push(*ptype as u8);
                out.push(u8::from(*sorted_front_coded));
                out.extend_from_slice(&block_size.to_le_bytes());
            }
            DictKind::Struct { table } => {
                out.push(2);
                table.encode(out);
            }
            DictKind::List {
                elem_dict_id,
                id_width,
            } => {
                out.push(3);
                out.extend_from_slice(&elem_dict_id.to_le_bytes());
                out.push(*id_width as u8);
                out.push(0); // reserved flags
            }
        }
    }

    pub fn decode(c: &mut Cursor<'_>) -> Result<Self, FormatError> {
        let name = c.read_string()?;
        let kind_tag = c.read_u8()?;
        let kind = match kind_tag {
            1 => {
                let ptype = PType::from_u8(c.read_u8()?)?;
                let flags = c.read_u8()?;
                let block_size = c.read_u32()?;
                DictKind::Flat {
                    ptype,
                    sorted_front_coded: (flags & 1) != 0,
                    block_size,
                }
            }
            2 => {
                let table = TableSchema::decode(c)?;
                DictKind::Struct { table }
            }
            3 => {
                let elem_dict_id = c.read_u16()?;
                let id_width = IdWidth::from_u8(c.read_u8()?)?;
                let _flags = c.read_u8()?;
                DictKind::List {
                    elem_dict_id,
                    id_width,
                }
            }
            _ => return Err(FormatError::InvalidDictKind(kind_tag)),
        };
        Ok(Self { name, kind })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DictKind {
    Flat {
        ptype: PType,
        sorted_front_coded: bool,
        block_size: u32,
    },
    Struct {
        table: TableSchema,
    },
    List {
        elem_dict_id: u16,
        id_width: IdWidth,
    },
}

/// Schema of a `ColumnTable` (root `RecordColumns` or a `StructDict`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TableSchema {
    pub column_count: u16,
    pub root: StructSchema,
}

impl TableSchema {
    pub fn encode(&self, out: &mut Vec<u8>) {
        out.extend_from_slice(&self.column_count.to_le_bytes());
        self.root.encode(out);
    }

    pub fn decode(c: &mut Cursor<'_>) -> Result<Self, FormatError> {
        let column_count = c.read_u16()?;
        let root = StructSchema::decode(c)?;
        Ok(Self { column_count, root })
    }

    /// Resolve and validate the physical column kind for every `col_id` in `0..column_count`.
    pub fn physical_column_kinds(
        &self,
        dict_count: usize,
    ) -> Result<Vec<PhysicalColKind>, FormatError> {
        let mut kinds: Vec<Option<PhysicalColKind>> = vec![None; self.column_count as usize];
        collect_struct_cols(&self.root, dict_count, &mut kinds)?;
        let mut out = Vec::with_capacity(self.column_count as usize);
        for (idx, k) in kinds.into_iter().enumerate() {
            match k {
                Some(kind) => out.push(kind),
                None => {
                    return Err(FormatError::InvalidSchema(format!(
                        "physical column {idx} is unreferenced in TableSchema"
                    )));
                }
            }
        }
        Ok(out)
    }
}

fn assign_col(
    kinds: &mut [Option<PhysicalColKind>],
    col_id: u16,
    kind: PhysicalColKind,
) -> Result<(), FormatError> {
    let idx = col_id as usize;
    if idx >= kinds.len() {
        return Err(FormatError::InvalidSchema(format!(
            "col_id {col_id} exceeds column_count {}",
            kinds.len()
        )));
    }
    if kinds[idx].is_some() {
        return Err(FormatError::InvalidSchema(format!(
            "duplicate physical col_id {col_id}"
        )));
    }
    kinds[idx] = Some(kind);
    Ok(())
}

fn collect_struct_cols(
    s: &StructSchema,
    dict_count: usize,
    kinds: &mut [Option<PhysicalColKind>],
) -> Result<(), FormatError> {
    if let Some(c) = s.presence_col {
        assign_col(kinds, c, PhysicalColKind::Primitive(PType::Bool))?;
    }
    for f in &s.fields {
        collect_col_type(&f.col_type, dict_count, kinds)?;
    }
    for g in &s.dict_groups {
        if (g.dict_id as usize) >= dict_count {
            return Err(FormatError::InvalidSchema(format!(
                "DictGroup references out-of-range dict_id {}",
                g.dict_id
            )));
        }
        assign_col(
            kinds,
            g.col_id,
            PhysicalColKind::Primitive(g.id_width.as_ptype()),
        )?;
    }
    Ok(())
}

fn collect_col_type(
    ct: &ColumnType,
    dict_count: usize,
    kinds: &mut [Option<PhysicalColKind>],
) -> Result<(), FormatError> {
    match ct {
        ColumnType::Primitive { ptype, col_id, .. } => {
            assign_col(kinds, *col_id, PhysicalColKind::Primitive(*ptype))
        }
        ColumnType::DictRef {
            dict_id,
            id_width,
            col_id,
            ..
        } => {
            if (*dict_id as usize) >= dict_count {
                return Err(FormatError::InvalidSchema(format!(
                    "DictRef references out-of-range dict_id {dict_id}"
                )));
            }
            assign_col(
                kinds,
                *col_id,
                PhysicalColKind::Primitive(id_width.as_ptype()),
            )
        }
        ColumnType::Struct(s) => collect_struct_cols(s, dict_count, kinds),
        ColumnType::ShreddedMap {
            presence_col,
            overflow_col,
            entries,
            ..
        } => {
            if let Some(c) = presence_col {
                assign_col(kinds, *c, PhysicalColKind::Primitive(PType::Bool))?;
            }
            if let Some(c) = overflow_col {
                assign_col(kinds, *c, PhysicalColKind::Dynamic)?;
            }
            for e in entries {
                collect_col_type(&e.value_type, dict_count, kinds)?;
            }
            Ok(())
        }
        ColumnType::List {
            offsets_col,
            elem_type,
            ..
        } => {
            assign_col(kinds, *offsets_col, PhysicalColKind::Primitive(PType::U32))?;
            collect_col_type(elem_type, dict_count, kinds)
        }
        ColumnType::Dynamic { col_id, .. } => assign_col(kinds, *col_id, PhysicalColKind::Dynamic),
    }
}

/// Struct schema (root or nested).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StructSchema {
    pub nullable: bool,
    pub presence_col: Option<u16>,
    pub fields: Vec<StructField>,
    pub dict_groups: Vec<DictGroup>,
}

impl StructSchema {
    pub fn encode(&self, out: &mut Vec<u8>) {
        let mut flags = 0u8;
        if self.nullable {
            flags |= 0x01;
        }
        if self.presence_col.is_some() {
            flags |= 0x02;
        }
        out.push(flags);
        if let Some(c) = self.presence_col {
            out.extend_from_slice(&c.to_le_bytes());
        }
        out.extend_from_slice(&(self.fields.len() as u16).to_le_bytes());
        for f in &self.fields {
            write_string(out, &f.name);
            f.col_type.encode(out);
        }
        out.extend_from_slice(&(self.dict_groups.len() as u16).to_le_bytes());
        for g in &self.dict_groups {
            g.encode(out);
        }
    }

    pub fn decode(c: &mut Cursor<'_>) -> Result<Self, FormatError> {
        let flags = c.read_u8()?;
        let nullable = (flags & 0x01) != 0;
        let presence_col = if (flags & 0x02) != 0 {
            Some(c.read_u16()?)
        } else {
            None
        };
        let field_count = c.read_u16()? as usize;
        let mut fields = Vec::with_capacity(field_count);
        for _ in 0..field_count {
            let name = c.read_string()?;
            let col_type = ColumnType::decode(c)?;
            fields.push(StructField { name, col_type });
        }
        let dg_count = c.read_u16()? as usize;
        let mut dict_groups = Vec::with_capacity(dg_count);
        for _ in 0..dg_count {
            dict_groups.push(DictGroup::decode(c)?);
        }
        Ok(Self {
            nullable,
            presence_col,
            fields,
            dict_groups,
        })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StructField {
    pub name: String,
    pub col_type: ColumnType,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DictGroup {
    pub dict_id: u16,
    pub id_width: IdWidth,
    pub col_id: u16,
    pub field_names: Vec<String>,
}

impl DictGroup {
    pub fn encode(&self, out: &mut Vec<u8>) {
        out.extend_from_slice(&self.dict_id.to_le_bytes());
        out.push(self.id_width as u8);
        out.extend_from_slice(&self.col_id.to_le_bytes());
        out.extend_from_slice(&(self.field_names.len() as u16).to_le_bytes());
        for name in &self.field_names {
            write_string(out, name);
        }
    }

    pub fn decode(c: &mut Cursor<'_>) -> Result<Self, FormatError> {
        let dict_id = c.read_u16()?;
        let id_width = IdWidth::from_u8(c.read_u8()?)?;
        let col_id = c.read_u16()?;
        let count = c.read_u16()? as usize;
        let mut field_names = Vec::with_capacity(count);
        for _ in 0..count {
            field_names.push(c.read_string()?);
        }
        Ok(Self {
            dict_id,
            id_width,
            col_id,
            field_names,
        })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ShreddedMapEntry {
    pub key: String,
    pub value_type: ColumnType,
}

/// The 6 orthogonal column primitives in COI Schema v1.0.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ColumnType {
    Primitive {
        ptype: PType,
        nullable: bool,
        col_id: u16,
    },
    DictRef {
        dict_id: u16,
        id_width: IdWidth,
        nullable: bool,
        col_id: u16,
    },
    Struct(StructSchema),
    ShreddedMap {
        nullable: bool,
        presence_col: Option<u16>,
        overflow_col: Option<u16>,
        entries: Vec<ShreddedMapEntry>,
    },
    List {
        nullable: bool,
        offsets_col: u16,
        elem_type: Box<ColumnType>,
    },
    Dynamic {
        nullable: bool,
        col_id: u16,
    },
}

impl ColumnType {
    pub fn encode(&self, out: &mut Vec<u8>) {
        match self {
            Self::Primitive {
                ptype,
                nullable,
                col_id,
            } => {
                out.push(1);
                out.push(*ptype as u8);
                out.push(u8::from(*nullable));
                out.extend_from_slice(&col_id.to_le_bytes());
            }
            Self::DictRef {
                dict_id,
                id_width,
                nullable,
                col_id,
            } => {
                out.push(2);
                out.extend_from_slice(&dict_id.to_le_bytes());
                out.push(*id_width as u8);
                out.push(u8::from(*nullable));
                out.extend_from_slice(&col_id.to_le_bytes());
            }
            Self::Struct(s) => {
                out.push(3);
                s.encode(out);
            }
            Self::ShreddedMap {
                nullable,
                presence_col,
                overflow_col,
                entries,
            } => {
                out.push(4);
                let mut flags = 0u8;
                if *nullable {
                    flags |= 0x01;
                }
                if presence_col.is_some() {
                    flags |= 0x02;
                }
                if overflow_col.is_some() {
                    flags |= 0x04;
                }
                out.push(flags);
                if let Some(c) = presence_col {
                    out.extend_from_slice(&c.to_le_bytes());
                }
                if let Some(c) = overflow_col {
                    out.extend_from_slice(&c.to_le_bytes());
                }
                out.extend_from_slice(&(entries.len() as u16).to_le_bytes());
                for e in entries {
                    write_string(out, &e.key);
                    e.value_type.encode(out);
                }
            }
            Self::List {
                nullable,
                offsets_col,
                elem_type,
            } => {
                out.push(5);
                out.push(u8::from(*nullable));
                out.extend_from_slice(&offsets_col.to_le_bytes());
                elem_type.encode(out);
            }
            Self::Dynamic { nullable, col_id } => {
                out.push(6);
                out.push(u8::from(*nullable));
                out.extend_from_slice(&col_id.to_le_bytes());
            }
        }
    }

    pub fn decode(c: &mut Cursor<'_>) -> Result<Self, FormatError> {
        let tag = c.read_u8()?;
        match tag {
            1 => Ok(Self::Primitive {
                ptype: PType::from_u8(c.read_u8()?)?,
                nullable: c.read_u8()? != 0,
                col_id: c.read_u16()?,
            }),
            2 => Ok(Self::DictRef {
                dict_id: c.read_u16()?,
                id_width: IdWidth::from_u8(c.read_u8()?)?,
                nullable: c.read_u8()? != 0,
                col_id: c.read_u16()?,
            }),
            3 => Ok(Self::Struct(StructSchema::decode(c)?)),
            4 => {
                let flags = c.read_u8()?;
                let nullable = (flags & 0x01) != 0;
                let presence_col = if (flags & 0x02) != 0 {
                    Some(c.read_u16()?)
                } else {
                    None
                };
                let overflow_col = if (flags & 0x04) != 0 {
                    Some(c.read_u16()?)
                } else {
                    None
                };
                let count = c.read_u16()? as usize;
                let mut entries = Vec::with_capacity(count);
                for _ in 0..count {
                    let key = c.read_string()?;
                    let value_type = ColumnType::decode(c)?;
                    entries.push(ShreddedMapEntry { key, value_type });
                }
                Ok(Self::ShreddedMap {
                    nullable,
                    presence_col,
                    overflow_col,
                    entries,
                })
            }
            5 => {
                let nullable = c.read_u8()? != 0;
                let offsets_col = c.read_u16()?;
                let elem_type = Box::new(ColumnType::decode(c)?);
                Ok(Self::List {
                    nullable,
                    offsets_col,
                    elem_type,
                })
            }
            6 => Ok(Self::Dynamic {
                nullable: c.read_u8()? != 0,
                col_id: c.read_u16()?,
            }),
            _ => Err(FormatError::InvalidColumnTag(tag)),
        }
    }
}