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;
#[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",
}
}
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,
}
}
pub const fn supports_delta(self) -> bool {
matches!(
self,
Self::U8 | Self::U16 | Self::U32 | Self::U64 | Self::I32 | Self::I64
)
}
}
#[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)),
}
}
#[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,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PhysicalColKind {
Primitive(PType),
Dynamic,
}
#[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)
}
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(())
}
}
#[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); }
}
}
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,
},
}
#[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 })
}
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),
}
}
#[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,
}
#[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)),
}
}
}