use std::collections::BTreeMap;
use std::sync::{Arc, OnceLock};
use coip_format::{
ChunkHeader, ColumnTableHeader, ColumnType, Cursor, DictKind, EncMode, FlatDictHeader,
FormatError, IdWidth, ListDictHeader, NullMode, PType, PhysicalColKind, Schema, StructSchema,
TableSchema, Value, read_svarint, read_uvarint,
};
use crate::cache::ShardedLruCache;
use crate::codec::decompress;
use crate::error::{ReaderError, Result};
use crate::projection::ProjectionNode;
use crate::source::Backing;
#[derive(Debug, Clone, Copy)]
pub enum ScalarRef<'a> {
Bool(bool),
U8(u8),
U16(u16),
U32(u32),
U64(u64),
U128(u128),
I32(i32),
I64(i64),
F32(f32),
F64(f64),
Utf8(&'a str),
Bytes(&'a [u8]),
Dynamic(&'a [u8]),
}
enum Validity {
AllValid,
AllNull,
Bitmap {
words: Vec<u64>,
word_ranks: Vec<u32>,
},
}
impl Validity {
fn from_bytes(bytes: &[u8]) -> Self {
let word_count = bytes.len().div_ceil(8);
let mut words = Vec::with_capacity(word_count);
let mut word_ranks = Vec::with_capacity(word_count);
let mut rank = 0u32;
for w in 0..word_count {
let start = w * 8;
let end = (start + 8).min(bytes.len());
let mut arr = [0u8; 8];
arr[..end - start].copy_from_slice(&bytes[start..end]);
let word = u64::from_le_bytes(arr);
words.push(word);
word_ranks.push(rank);
rank += word.count_ones();
}
Self::Bitmap { words, word_ranks }
}
#[inline]
fn valid_count(&self, total_rows: usize) -> usize {
match self {
Self::AllValid => total_rows,
Self::AllNull => 0,
Self::Bitmap { words, word_ranks } => {
if words.is_empty() {
0
} else {
let last = words.len() - 1;
(word_ranks[last] + words[last].count_ones()) as usize
}
}
}
}
#[inline]
fn dense_index(&self, idx: usize) -> Option<usize> {
match self {
Self::AllValid => Some(idx),
Self::AllNull => None,
Self::Bitmap { words, word_ranks } => {
let w = idx >> 6;
let b = idx & 63;
let word = *words.get(w)?;
if ((word >> b) & 1) == 0 {
return None;
}
let mask = (1u64 << b) - 1;
let rank = word_ranks[w] + (word & mask).count_ones();
Some(rank as usize)
}
}
}
}
enum DecodedValues {
Empty,
ConstBool(bool),
ConstU8(u8),
ConstU16(u16),
ConstU32(u32),
ConstU64(u64),
ConstU128(u128),
ConstI32(i32),
ConstI64(i64),
ConstF32(f32),
ConstF64(f64),
ConstBytes(Vec<u8>),
Bool(Vec<u8>),
U8(Vec<u8>),
U16(Vec<u16>),
U32(Vec<u32>),
U64(Vec<u64>),
U128(Vec<u128>),
I32(Vec<i32>),
I64(Vec<i64>),
F32(Vec<f32>),
F64(Vec<f64>),
VarBytes { offsets: Vec<u32>, data: Vec<u8> },
}
impl DecodedValues {
#[inline]
fn get_scalar_ref(&self, dense_idx: usize, kind: PhysicalColKind) -> Result<ScalarRef<'_>> {
match (self, kind) {
(Self::ConstBool(v), _) => Ok(ScalarRef::Bool(*v)),
(Self::ConstU8(v), _) => Ok(ScalarRef::U8(*v)),
(Self::ConstU16(v), _) => Ok(ScalarRef::U16(*v)),
(Self::ConstU32(v), _) => Ok(ScalarRef::U32(*v)),
(Self::ConstU64(v), _) => Ok(ScalarRef::U64(*v)),
(Self::ConstU128(v), _) => Ok(ScalarRef::U128(*v)),
(Self::ConstI32(v), _) => Ok(ScalarRef::I32(*v)),
(Self::ConstI64(v), _) => Ok(ScalarRef::I64(*v)),
(Self::ConstF32(v), _) => Ok(ScalarRef::F32(*v)),
(Self::ConstF64(v), _) => Ok(ScalarRef::F64(*v)),
(Self::ConstBytes(b), PhysicalColKind::Primitive(PType::Utf8)) => {
let s = std::str::from_utf8(b).map_err(|_| FormatError::InvalidUtf8)?;
Ok(ScalarRef::Utf8(s))
}
(Self::ConstBytes(b), PhysicalColKind::Primitive(PType::Bytes)) => {
Ok(ScalarRef::Bytes(b))
}
(Self::ConstBytes(b), PhysicalColKind::Dynamic) => Ok(ScalarRef::Dynamic(b)),
(Self::Bool(bits), _) => {
let byte = *bits
.get(dense_idx >> 3)
.ok_or_else(|| ReaderError::Corrupt("bool index OOB".into()))?;
Ok(ScalarRef::Bool(((byte >> (dense_idx & 7)) & 1) != 0))
}
(Self::U8(v), _) => Ok(ScalarRef::U8(v[dense_idx])),
(Self::U16(v), _) => Ok(ScalarRef::U16(v[dense_idx])),
(Self::U32(v), _) => Ok(ScalarRef::U32(v[dense_idx])),
(Self::U64(v), _) => Ok(ScalarRef::U64(v[dense_idx])),
(Self::U128(v), _) => Ok(ScalarRef::U128(v[dense_idx])),
(Self::I32(v), _) => Ok(ScalarRef::I32(v[dense_idx])),
(Self::I64(v), _) => Ok(ScalarRef::I64(v[dense_idx])),
(Self::F32(v), _) => Ok(ScalarRef::F32(v[dense_idx])),
(Self::F64(v), _) => Ok(ScalarRef::F64(v[dense_idx])),
(Self::VarBytes { offsets, data }, PhysicalColKind::Primitive(PType::Utf8)) => {
let s = offsets[dense_idx] as usize;
let e = offsets[dense_idx + 1] as usize;
let str_slice =
std::str::from_utf8(&data[s..e]).map_err(|_| FormatError::InvalidUtf8)?;
Ok(ScalarRef::Utf8(str_slice))
}
(Self::VarBytes { offsets, data }, PhysicalColKind::Primitive(PType::Bytes)) => {
let s = offsets[dense_idx] as usize;
let e = offsets[dense_idx + 1] as usize;
Ok(ScalarRef::Bytes(&data[s..e]))
}
(Self::VarBytes { offsets, data }, PhysicalColKind::Dynamic) => {
let s = offsets[dense_idx] as usize;
let e = offsets[dense_idx + 1] as usize;
Ok(ScalarRef::Dynamic(&data[s..e]))
}
_ => Err(ReaderError::Corrupt(
"decoded chunk value kind mismatch".into(),
)),
}
}
#[inline]
fn get_as_value(&self, dense_idx: usize, kind: PhysicalColKind) -> Result<Value> {
match self.get_scalar_ref(dense_idx, kind)? {
ScalarRef::Bool(v) => Ok(Value::Bool(v)),
ScalarRef::U8(v) => Ok(Value::U8(v)),
ScalarRef::U16(v) => Ok(Value::U16(v)),
ScalarRef::U32(v) => Ok(Value::U32(v)),
ScalarRef::U64(v) => Ok(Value::U64(v)),
ScalarRef::U128(v) => Ok(Value::U128(v)),
ScalarRef::I32(v) => Ok(Value::I32(v)),
ScalarRef::I64(v) => Ok(Value::I64(v)),
ScalarRef::F32(v) => Ok(Value::F32(v)),
ScalarRef::F64(v) => Ok(Value::F64(v)),
ScalarRef::Utf8(s) => Ok(Value::Utf8(s.to_owned())),
ScalarRef::Bytes(b) => Ok(Value::Bytes(b.to_vec())),
ScalarRef::Dynamic(b) => Ok(Value::decode_exact(b)?),
}
}
#[inline]
fn get_u32_id(&self, dense_idx: usize) -> Result<u32> {
match self {
Self::ConstU8(v) => Ok(*v as u32),
Self::ConstU16(v) => Ok(*v as u32),
Self::ConstU32(v) => Ok(*v),
Self::U8(v) => Ok(v[dense_idx] as u32),
Self::U16(v) => Ok(v[dense_idx] as u32),
Self::U32(v) => Ok(v[dense_idx]),
_ => Err(ReaderError::Corrupt(
"expected U8/U16/U32 dict ID column".into(),
)),
}
}
#[inline]
fn get_bool(&self, dense_idx: usize) -> Result<bool> {
match self {
Self::ConstBool(v) => Ok(*v),
Self::Bool(bits) => Ok(((bits[dense_idx >> 3] >> (dense_idx & 7)) & 1) != 0),
_ => Err(ReaderError::Corrupt("expected Bool presence column".into())),
}
}
}
pub struct DecodedChunk {
validity: Validity,
values: DecodedValues,
kind: PhysicalColKind,
}
impl DecodedChunk {
#[inline]
pub fn get_scalar_ref(&self, row_in_rg: usize) -> Result<Option<ScalarRef<'_>>> {
let Some(dense) = self.validity.dense_index(row_in_rg) else {
return Ok(None);
};
Ok(Some(self.values.get_scalar_ref(dense, self.kind)?))
}
#[inline]
pub fn get_value(&self, row_in_rg: usize) -> Result<Option<Value>> {
let Some(dense) = self.validity.dense_index(row_in_rg) else {
return Ok(None);
};
Ok(Some(self.values.get_as_value(dense, self.kind)?))
}
#[inline]
pub fn get_u32(&self, row_in_rg: usize) -> Result<Option<u32>> {
let Some(dense) = self.validity.dense_index(row_in_rg) else {
return Ok(None);
};
Ok(Some(self.values.get_u32_id(dense)?))
}
#[inline]
pub fn get_bool(&self, row_in_rg: usize) -> Result<Option<bool>> {
let Some(dense) = self.validity.dense_index(row_in_rg) else {
return Ok(None);
};
Ok(Some(self.values.get_bool(dense)?))
}
pub fn list_range_in_rg(
&self,
row_in_rg: usize,
rows_in_rg: usize,
) -> Result<Option<(usize, usize, usize)>> {
let Some(target_len) = self.get_u32(row_in_rg)? else {
return Ok(None);
};
let mut start = 0usize;
let mut total = 0usize;
for r in 0..rows_in_rg {
if let Some(len) = self.get_u32(r)? {
if r < row_in_rg {
start += len as usize;
}
total += len as usize;
}
}
Ok(Some((start, target_len as usize, total)))
}
}
pub struct ChunkCache {
inner: ShardedLruCache<(u32, u16, u32), Arc<DecodedChunk>>,
}
impl ChunkCache {
pub fn new(cap: usize) -> Self {
Self {
inner: ShardedLruCache::new(cap),
}
}
pub fn clear(&self) {
self.inner.clear();
}
}
pub struct ColumnTableReader {
table_id: u32,
pub header: ColumnTableHeader,
col_kinds: Vec<PhysicalColKind>,
chunk_offsets: Vec<u64>,
chunks_base_offset: u64,
single_rg_cache: Option<Vec<OnceLock<Arc<DecodedChunk>>>>,
}
impl ColumnTableReader {
pub fn parse(
table_id: u32,
backing: &Backing<'_>,
offset: u64,
len: u64,
table_schema: &TableSchema,
dict_count: usize,
) -> Result<Self> {
let hdr_bytes = backing.read_slice(offset, coip_format::COLUMN_TABLE_HEADER_SIZE)?;
let mut c = Cursor::new(&hdr_bytes);
let header = ColumnTableHeader::decode(&mut c)?;
if header.column_count != table_schema.column_count {
return Err(ReaderError::Corrupt(format!(
"ColumnTable column_count {} != schema {}",
header.column_count, table_schema.column_count
)));
}
let col_kinds = table_schema.physical_column_kinds(dict_count)?;
let offsets_count = (header.column_count as usize) * (header.row_group_count as usize + 1);
let offsets_bytes_len = offsets_count * 8;
let offsets_pos = offset + (coip_format::COLUMN_TABLE_HEADER_SIZE as u64);
if (coip_format::COLUMN_TABLE_HEADER_SIZE as u64) + (offsets_bytes_len as u64) > len {
return Err(FormatError::UnexpectedEof.into());
}
let off_bytes = backing.read_slice(offsets_pos, offsets_bytes_len)?;
let mut oc = Cursor::new(&off_bytes);
let mut chunk_offsets = Vec::with_capacity(offsets_count);
for _ in 0..offsets_count {
chunk_offsets.push(oc.read_u64()?);
}
let chunks_base_offset = offsets_pos + (offsets_bytes_len as u64);
let single_rg_cache = if header.row_group_count == 1 && header.row_count <= 4096 {
Some(
(0..header.column_count as usize)
.map(|_| OnceLock::new())
.collect(),
)
} else {
None
};
Ok(Self {
table_id,
header,
col_kinds,
chunk_offsets,
chunks_base_offset,
single_rg_cache,
})
}
pub fn get_chunk(
&self,
backing: &Backing<'_>,
cache: &ChunkCache,
col_id: u16,
rg: u32,
rows_in_chunk: usize,
) -> Result<Arc<DecodedChunk>> {
if let Some(slots) = &self.single_rg_cache {
let slot = &slots[col_id as usize];
if let Some(hit) = slot.get() {
return Ok(Arc::clone(hit));
}
let decoded =
Arc::new(self.decode_chunk_uncached(backing, col_id, rg, rows_in_chunk)?);
let stored = slot.get_or_init(|| decoded);
return Ok(Arc::clone(stored));
}
let key = (self.table_id, col_id, rg);
if let Some(hit) = cache.inner.get(&key) {
return Ok(hit);
}
let decoded = Arc::new(self.decode_chunk_uncached(backing, col_id, rg, rows_in_chunk)?);
cache.inner.put(key, Arc::clone(&decoded));
Ok(decoded)
}
fn decode_chunk_uncached(
&self,
backing: &Backing<'_>,
col_id: u16,
rg: u32,
rows_in_chunk: usize,
) -> Result<DecodedChunk> {
let stride = self.header.row_group_count as usize + 1;
let idx = (col_id as usize) * stride + (rg as usize);
let rel_start = self.chunk_offsets[idx];
let rel_end = self.chunk_offsets[idx + 1];
let chunk_len = (rel_end - rel_start) as usize;
let raw = backing.read_slice(self.chunks_base_offset + rel_start, chunk_len)?;
let kind = self.col_kinds[col_id as usize];
decode_chunk(&raw, rows_in_chunk, kind)
}
#[inline]
pub fn row_group_of(&self, row_idx: usize) -> (u32, usize, usize) {
let rg_size = self.header.row_group_size as usize;
let rg = (row_idx / rg_size) as u32;
let row_in_rg = row_idx % rg_size;
let rows_in_rg = self.header.rows_in_rg(rg);
(rg, row_in_rg, rows_in_rg)
}
}
fn decode_chunk(raw: &[u8], rows_in_chunk: usize, kind: PhysicalColKind) -> Result<DecodedChunk> {
let hdr = ChunkHeader::decode(raw)?;
if hdr.null_mode == NullMode::AllNull {
return Ok(DecodedChunk {
validity: Validity::AllNull,
values: DecodedValues::Empty,
kind,
});
}
let body = decompress(hdr.codec, &raw[3..], None)?;
let mut pos = 0usize;
let validity = match hdr.null_mode {
NullMode::AllValid => Validity::AllValid,
NullMode::AllNull => unreachable!(),
NullMode::ValidityBitmap => {
let bm_len = rows_in_chunk.div_ceil(8);
if pos + bm_len > body.len() {
return Err(FormatError::UnexpectedEof.into());
}
let v = Validity::from_bytes(&body[pos..pos + bm_len]);
pos += bm_len;
v
}
};
let valid_count = validity.valid_count(rows_in_chunk);
let val_bytes = &body[pos..];
let values = if valid_count == 0 {
DecodedValues::Empty
} else {
decode_values(val_bytes, valid_count, hdr.enc_mode, kind)?
};
Ok(DecodedChunk {
validity,
values,
kind,
})
}
fn decode_values(
buf: &[u8],
count: usize,
enc_mode: EncMode,
kind: PhysicalColKind,
) -> Result<DecodedValues> {
let mut c = Cursor::new(buf);
match enc_mode {
EncMode::Constant => match kind {
PhysicalColKind::Primitive(PType::Bool) => {
Ok(DecodedValues::ConstBool(c.read_u8()? != 0))
}
PhysicalColKind::Primitive(PType::U8) => Ok(DecodedValues::ConstU8(c.read_u8()?)),
PhysicalColKind::Primitive(PType::U16) => Ok(DecodedValues::ConstU16(c.read_u16()?)),
PhysicalColKind::Primitive(PType::U32) => Ok(DecodedValues::ConstU32(c.read_u32()?)),
PhysicalColKind::Primitive(PType::U64) => Ok(DecodedValues::ConstU64(c.read_u64()?)),
PhysicalColKind::Primitive(PType::U128) => Ok(DecodedValues::ConstU128(c.read_u128()?)),
PhysicalColKind::Primitive(PType::I32) => Ok(DecodedValues::ConstI32(c.read_i32()?)),
PhysicalColKind::Primitive(PType::I64) => Ok(DecodedValues::ConstI64(c.read_i64()?)),
PhysicalColKind::Primitive(PType::F32) => Ok(DecodedValues::ConstF32(c.read_f32()?)),
PhysicalColKind::Primitive(PType::F64) => Ok(DecodedValues::ConstF64(c.read_f64()?)),
PhysicalColKind::Primitive(PType::Utf8 | PType::Bytes) | PhysicalColKind::Dynamic => {
let len = c.read_uvarint()? as usize;
Ok(DecodedValues::ConstBytes(c.read_bytes(len)?.to_vec()))
}
},
EncMode::Plain => decode_plain_values(&mut c, count, kind),
EncMode::Delta => decode_delta_values(buf, count, kind),
EncMode::Rle => decode_rle_values(&mut c, count, kind),
}
}
fn decode_plain_values(
c: &mut Cursor<'_>,
count: usize,
kind: PhysicalColKind,
) -> Result<DecodedValues> {
match kind {
PhysicalColKind::Primitive(PType::Bool) => {
let bytes = c.read_bytes(count.div_ceil(8))?.to_vec();
Ok(DecodedValues::Bool(bytes))
}
PhysicalColKind::Primitive(PType::U8) => {
Ok(DecodedValues::U8(c.read_bytes(count)?.to_vec()))
}
PhysicalColKind::Primitive(PType::U16) => {
let raw = c.read_bytes(count * 2)?;
let v = raw
.chunks_exact(2)
.map(|b| u16::from_le_bytes([b[0], b[1]]))
.collect();
Ok(DecodedValues::U16(v))
}
PhysicalColKind::Primitive(PType::U32) => {
let raw = c.read_bytes(count * 4)?;
let v = raw
.chunks_exact(4)
.map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
.collect();
Ok(DecodedValues::U32(v))
}
PhysicalColKind::Primitive(PType::U64) => {
let raw = c.read_bytes(count * 8)?;
let v = raw
.chunks_exact(8)
.map(|b| u64::from_le_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]))
.collect();
Ok(DecodedValues::U64(v))
}
PhysicalColKind::Primitive(PType::U128) => {
let raw = c.read_bytes(count * 16)?;
let v = raw
.chunks_exact(16)
.map(|b| u128::from_le_bytes(b.try_into().unwrap()))
.collect();
Ok(DecodedValues::U128(v))
}
PhysicalColKind::Primitive(PType::I32) => {
let raw = c.read_bytes(count * 4)?;
let v = raw
.chunks_exact(4)
.map(|b| i32::from_le_bytes([b[0], b[1], b[2], b[3]]))
.collect();
Ok(DecodedValues::I32(v))
}
PhysicalColKind::Primitive(PType::I64) => {
let raw = c.read_bytes(count * 8)?;
let v = raw
.chunks_exact(8)
.map(|b| i64::from_le_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]))
.collect();
Ok(DecodedValues::I64(v))
}
PhysicalColKind::Primitive(PType::F32) => {
let raw = c.read_bytes(count * 4)?;
let v = raw
.chunks_exact(4)
.map(|b| f32::from_bits(u32::from_le_bytes([b[0], b[1], b[2], b[3]])))
.collect();
Ok(DecodedValues::F32(v))
}
PhysicalColKind::Primitive(PType::F64) => {
let raw = c.read_bytes(count * 8)?;
let v = raw
.chunks_exact(8)
.map(|b| {
f64::from_bits(u64::from_le_bytes([
b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7],
]))
})
.collect();
Ok(DecodedValues::F64(v))
}
PhysicalColKind::Primitive(PType::Utf8 | PType::Bytes) | PhysicalColKind::Dynamic => {
let mut offsets = Vec::with_capacity(count + 1);
let mut total = 0u32;
offsets.push(0);
for _ in 0..count {
let len = c.read_uvarint()? as u32;
total = total
.checked_add(len)
.ok_or_else(|| ReaderError::Corrupt("varbytes offset overflow".into()))?;
offsets.push(total);
}
let data = c.read_bytes(total as usize)?.to_vec();
Ok(DecodedValues::VarBytes { offsets, data })
}
}
}
fn decode_delta_values(buf: &[u8], count: usize, kind: PhysicalColKind) -> Result<DecodedValues> {
let signed = matches!(kind, PhysicalColKind::Primitive(PType::I32 | PType::I64));
let mut pos = 0usize;
let mut cur: u64 = if signed {
let (v, u) = read_svarint(&buf[pos..])?;
pos += u;
v as u64
} else {
let (v, u) = read_uvarint(&buf[pos..])?;
pos += u;
v
};
macro_rules! decode_int_delta {
($variant:ident, $ty:ty) => {{
let mut v = Vec::with_capacity(count);
v.push(cur as $ty);
for _ in 1..count {
let (d, u) = read_svarint(&buf[pos..])?;
pos += u;
cur = cur.wrapping_add(d as u64);
v.push(cur as $ty);
}
Ok(DecodedValues::$variant(v))
}};
}
match kind {
PhysicalColKind::Primitive(PType::U8) => decode_int_delta!(U8, u8),
PhysicalColKind::Primitive(PType::U16) => decode_int_delta!(U16, u16),
PhysicalColKind::Primitive(PType::U32) => decode_int_delta!(U32, u32),
PhysicalColKind::Primitive(PType::U64) => decode_int_delta!(U64, u64),
PhysicalColKind::Primitive(PType::I32) => decode_int_delta!(I32, i32),
PhysicalColKind::Primitive(PType::I64) => decode_int_delta!(I64, i64),
_ => Err(ReaderError::Corrupt(
"Delta encoding on non-integer column".into(),
)),
}
}
fn decode_rle_values(
c: &mut Cursor<'_>,
count: usize,
kind: PhysicalColKind,
) -> Result<DecodedValues> {
macro_rules! decode_fixed_rle {
($variant:ident, $read_fn:ident) => {{
let mut v = Vec::with_capacity(count);
while v.len() < count {
let val = c.$read_fn()?;
let run = c.read_uvarint()? as usize;
if v.len() + run > count {
return Err(ReaderError::Corrupt("RLE run overflow".into()));
}
v.resize(v.len() + run, val);
}
Ok(DecodedValues::$variant(v))
}};
}
match kind {
PhysicalColKind::Primitive(PType::Bool) => {
let mut bits = vec![0u8; count.div_ceil(8)];
let mut idx = 0usize;
while idx < count {
let val = c.read_u8()? != 0;
let run = c.read_uvarint()? as usize;
if idx + run > count {
return Err(ReaderError::Corrupt("Bool RLE overflow".into()));
}
if val {
for i in idx..idx + run {
bits[i >> 3] |= 1u8 << (i & 7);
}
}
idx += run;
}
Ok(DecodedValues::Bool(bits))
}
PhysicalColKind::Primitive(PType::U8) => decode_fixed_rle!(U8, read_u8),
PhysicalColKind::Primitive(PType::U16) => decode_fixed_rle!(U16, read_u16),
PhysicalColKind::Primitive(PType::U32) => decode_fixed_rle!(U32, read_u32),
PhysicalColKind::Primitive(PType::U64) => decode_fixed_rle!(U64, read_u64),
PhysicalColKind::Primitive(PType::U128) => decode_fixed_rle!(U128, read_u128),
PhysicalColKind::Primitive(PType::I32) => decode_fixed_rle!(I32, read_i32),
PhysicalColKind::Primitive(PType::I64) => decode_fixed_rle!(I64, read_i64),
PhysicalColKind::Primitive(PType::F32) => decode_fixed_rle!(F32, read_f32),
PhysicalColKind::Primitive(PType::F64) => decode_fixed_rle!(F64, read_f64),
PhysicalColKind::Primitive(PType::Utf8 | PType::Bytes) | PhysicalColKind::Dynamic => {
let mut offsets = Vec::with_capacity(count + 1);
let mut data = Vec::new();
offsets.push(0);
let mut seen = 0usize;
while seen < count {
let len = c.read_uvarint()? as usize;
let bytes = c.read_bytes(len)?;
let run = c.read_uvarint()? as usize;
if seen + run > count {
return Err(ReaderError::Corrupt("VarBytes RLE overflow".into()));
}
for _ in 0..run {
data.extend_from_slice(bytes);
offsets.push(data.len() as u32);
}
seen += run;
}
Ok(DecodedValues::VarBytes { offsets, data })
}
}
}
pub struct DecodedFlatBlock {
values: DecodedValues,
ptype: PType,
}
impl DecodedFlatBlock {
#[inline]
pub fn get_scalar_ref(&self, idx: usize) -> Result<ScalarRef<'_>> {
self.values
.get_scalar_ref(idx, PhysicalColKind::Primitive(self.ptype))
}
#[inline]
fn get(&self, idx: usize) -> Result<Value> {
self.values
.get_as_value(idx, PhysicalColKind::Primitive(self.ptype))
}
}
pub struct FlatDictReader {
header: FlatDictHeader,
ptype: PType,
block_offsets: Vec<u64>,
blocks_base_offset: u64,
single_block: OnceLock<Arc<DecodedFlatBlock>>,
block_cache: Option<ShardedLruCache<u32, Arc<DecodedFlatBlock>>>,
}
impl FlatDictReader {
fn parse(
backing: &Backing<'_>,
offset: u64,
len: u64,
ptype: PType,
cache_blocks: usize,
) -> Result<Self> {
let hdr_bytes = backing.read_slice(offset, coip_format::FLAT_DICT_HEADER_SIZE)?;
let mut c = Cursor::new(&hdr_bytes);
let header = FlatDictHeader::decode(&mut c)?;
let offsets_bytes_len = (header.block_count as usize + 1) * 8;
let off_pos = offset + (coip_format::FLAT_DICT_HEADER_SIZE as u64);
if (coip_format::FLAT_DICT_HEADER_SIZE as u64) + (offsets_bytes_len as u64) > len {
return Err(FormatError::UnexpectedEof.into());
}
let off_bytes = backing.read_slice(off_pos, offsets_bytes_len)?;
let mut oc = Cursor::new(&off_bytes);
let mut block_offsets = Vec::with_capacity(header.block_count as usize + 1);
for _ in 0..=header.block_count {
block_offsets.push(oc.read_u64()?);
}
let blocks_base_offset = off_pos + (offsets_bytes_len as u64);
let block_cache = if header.block_size > 0 {
Some(ShardedLruCache::new(cache_blocks))
} else {
None
};
Ok(Self {
header,
ptype,
block_offsets,
blocks_base_offset,
single_block: OnceLock::new(),
block_cache,
})
}
pub fn entry_count(&self) -> u64 {
self.header.entry_count
}
pub fn clear_cache(&self) {
if let Some(cache) = &self.block_cache {
cache.clear();
}
}
pub fn get_block_and_index(
&self,
backing: &Backing<'_>,
entry_idx: usize,
) -> Result<(Arc<DecodedFlatBlock>, usize)> {
if (entry_idx as u64) >= self.header.entry_count {
return Err(ReaderError::Corrupt("FlatDict entry_idx OOB".into()));
}
if self.header.block_size == 0 {
if let Some(blk) = self.single_block.get() {
return Ok((Arc::clone(blk), entry_idx));
}
let decoded = Arc::new(self.decode_block(backing, 0)?);
let blk = self.single_block.get_or_init(|| decoded);
return Ok((Arc::clone(blk), entry_idx));
}
let bs = self.header.block_size as usize;
let block_idx = (entry_idx / bs) as u32;
let local_idx = entry_idx % bs;
let cache = self.block_cache.as_ref().unwrap();
if let Some(hit) = cache.get(&block_idx) {
return Ok((hit, local_idx));
}
let decoded = Arc::new(self.decode_block(backing, block_idx)?);
cache.put(block_idx, Arc::clone(&decoded));
Ok((decoded, local_idx))
}
pub fn get(&self, backing: &Backing<'_>, entry_idx: usize) -> Result<Value> {
let (blk, local_idx) = self.get_block_and_index(backing, entry_idx)?;
blk.get(local_idx)
}
fn decode_block(&self, backing: &Backing<'_>, block_idx: u32) -> Result<DecodedFlatBlock> {
let b = block_idx as usize;
let rel_start = self.block_offsets[b];
let rel_end = self.block_offsets[b + 1];
let raw = backing.read_slice(
self.blocks_base_offset + rel_start,
(rel_end - rel_start) as usize,
)?;
let decomp = decompress(self.header.codec, &raw, None)?;
let count = self.header.entries_in_block(block_idx);
let values =
if self.header.sorted_front_coded && matches!(self.ptype, PType::Utf8 | PType::Bytes) {
decode_front_coded(&decomp, count)?
} else {
let mut c = Cursor::new(&decomp);
decode_plain_values(&mut c, count, PhysicalColKind::Primitive(self.ptype))?
};
Ok(DecodedFlatBlock {
values,
ptype: self.ptype,
})
}
}
fn decode_front_coded(buf: &[u8], count: usize) -> Result<DecodedValues> {
let mut c = Cursor::new(buf);
let mut offsets = Vec::with_capacity(count + 1);
let mut data = Vec::with_capacity(buf.len() * 2);
offsets.push(0u32);
if count == 0 {
return Ok(DecodedValues::VarBytes { offsets, data });
}
let first_len = c.read_uvarint()? as usize;
let first = c.read_bytes(first_len)?;
data.extend_from_slice(first);
offsets.push(data.len() as u32);
let mut prev_start = 0usize;
let mut prev_end = first_len;
for _ in 1..count {
let shared = c.read_uvarint()? as usize;
let suffix_len = c.read_uvarint()? as usize;
let suffix = c.read_bytes(suffix_len)?;
if shared > prev_end - prev_start {
return Err(ReaderError::Corrupt("front-coded shared prefix OOB".into()));
}
let cur_start = data.len();
data.reserve(shared + suffix_len);
data.extend_from_within(prev_start..prev_start + shared);
data.extend_from_slice(suffix);
let cur_end = data.len();
offsets.push(cur_end as u32);
prev_start = cur_start;
prev_end = cur_end;
}
Ok(DecodedValues::VarBytes { offsets, data })
}
struct DecodedListDict {
offsets: Vec<u32>,
elems: Vec<u32>,
}
pub struct ListDictReader {
header: ListDictHeader,
pub elem_dict_id: u16,
blob_offset: u64,
blob_len: u64,
loaded: OnceLock<Arc<DecodedListDict>>,
}
impl ListDictReader {
fn parse(backing: &Backing<'_>, offset: u64, len: u64, elem_dict_id: u16) -> Result<Self> {
let hdr_bytes = backing.read_slice(offset, coip_format::LIST_DICT_HEADER_SIZE)?;
let mut c = Cursor::new(&hdr_bytes);
let header = ListDictHeader::decode(&mut c)?;
Ok(Self {
header,
elem_dict_id,
blob_offset: offset,
blob_len: len,
loaded: OnceLock::new(),
})
}
pub fn entry_count(&self) -> u64 {
self.header.entry_count
}
fn get_loaded(&self, backing: &Backing<'_>) -> Result<&Arc<DecodedListDict>> {
if let Some(d) = self.loaded.get() {
return Ok(d);
}
let body_start = self.blob_offset + (coip_format::LIST_DICT_HEADER_SIZE as u64);
let body_len = (self.blob_len as usize)
.checked_sub(coip_format::LIST_DICT_HEADER_SIZE)
.ok_or(FormatError::UnexpectedEof)?;
let raw = backing.read_slice(body_start, body_len)?;
let off_len = self.header.offsets_len as usize;
if off_len > raw.len() {
return Err(FormatError::OutOfBounds("ListDict offsets_len").into());
}
let raw_offs = decompress(self.header.codec, &raw[..off_len], None)?;
let raw_elems = decompress(self.header.codec, &raw[off_len..], None)?;
let count = self.header.entry_count as usize;
let mut offsets = Vec::with_capacity(count + 1);
offsets.push(0u32);
let mut pos = 0usize;
let mut acc = 0u32;
for _ in 0..count {
let (len, u) = read_uvarint(&raw_offs[pos..])?;
pos += u;
acc += len as u32;
offsets.push(acc);
}
let total = self.header.total_elems as usize;
let mut ec = Cursor::new(&raw_elems);
let mut elems = Vec::with_capacity(total);
for _ in 0..total {
let id = match self.header.id_width {
IdWidth::U8 => ec.read_u8()? as u32,
IdWidth::U16 => ec.read_u16()? as u32,
IdWidth::U32 => ec.read_u32()?,
};
elems.push(id);
}
let decoded = Arc::new(DecodedListDict { offsets, elems });
Ok(self.loaded.get_or_init(|| decoded))
}
pub fn get_elem_slice(&self, backing: &Backing<'_>, entry_idx: usize) -> Result<&[u32]> {
let data = self.get_loaded(backing)?;
if entry_idx + 1 >= data.offsets.len() {
return Err(ReaderError::Corrupt("ListDict entry_idx OOB".into()));
}
let s = data.offsets[entry_idx] as usize;
let e = data.offsets[entry_idx + 1] as usize;
Ok(&data.elems[s..e])
}
pub fn get_elem_ids(&self, backing: &Backing<'_>, entry_idx: usize) -> Result<Vec<u32>> {
Ok(self.get_elem_slice(backing, entry_idx)?.to_vec())
}
}
pub enum DictReader {
Flat(Box<FlatDictReader>),
Struct {
table: ColumnTableReader,
schema: TableSchema,
},
List(ListDictReader),
}
impl DictReader {
pub fn entry_count(&self) -> u64 {
match self {
Self::Flat(f) => f.entry_count(),
Self::Struct { table, .. } => table.header.row_count,
Self::List(l) => l.entry_count(),
}
}
pub fn clear_cache(&self) {
if let Self::Flat(f) = self {
f.clear_cache();
}
}
}
pub struct DictTablesReader {
pub dicts: Vec<DictReader>,
}
impl DictTablesReader {
pub fn empty() -> Self {
Self { dicts: Vec::new() }
}
pub fn parse(
backing: &Backing<'_>,
section_offset: u64,
section_len: u64,
schema: &Schema,
flat_dict_cache_blocks: usize,
) -> Result<Self> {
let hdr_bytes = backing.read_slice(section_offset, 8)?;
let dict_count = u16::from_le_bytes([hdr_bytes[0], hdr_bytes[1]]) as usize;
if dict_count != schema.dicts.len() {
return Err(ReaderError::Corrupt(format!(
"DictTables count {dict_count} != schema {}",
schema.dicts.len()
)));
}
let dir_len = dict_count * 16;
if 8 + (dir_len as u64) > section_len {
return Err(FormatError::UnexpectedEof.into());
}
let dir_bytes = backing.read_slice(section_offset + 8, dir_len)?;
let mut c = Cursor::new(&dir_bytes);
let mut entries = Vec::with_capacity(dict_count);
for _ in 0..dict_count {
let off = c.read_u64()?;
let len = c.read_u64()?;
entries.push((off, len));
}
let blobs_base = section_offset + 8 + (dir_len as u64);
let mut dicts = Vec::with_capacity(dict_count);
for (idx, (rel_off, blob_len)) in entries.into_iter().enumerate() {
let abs_off = blobs_base + rel_off;
let ds = &schema.dicts[idx];
let reader = match &ds.kind {
DictKind::Flat { ptype, .. } => DictReader::Flat(Box::new(FlatDictReader::parse(
backing,
abs_off,
blob_len,
*ptype,
flat_dict_cache_blocks,
)?)),
DictKind::Struct { table } => DictReader::Struct {
table: ColumnTableReader::parse(
(idx + 1) as u32,
backing,
abs_off,
blob_len,
table,
schema.dicts.len(),
)?,
schema: table.clone(),
},
DictKind::List { elem_dict_id, .. } => DictReader::List(ListDictReader::parse(
backing,
abs_off,
blob_len,
*elem_dict_id,
)?),
};
dicts.push(reader);
}
Ok(Self { dicts })
}
}
#[allow(clippy::too_many_arguments)]
pub fn read_struct_row(
backing: &Backing<'_>,
table: &ColumnTableReader,
dicts: &DictTablesReader,
chunk_cache: &ChunkCache,
schema: &StructSchema,
rg: u32,
row_in_rg: usize,
rows_in_rg: usize,
proj: &ProjectionNode,
) -> Result<Option<BTreeMap<String, Value>>> {
let explicit_present = if let Some(pcol) = schema.presence_col {
let chunk = table.get_chunk(backing, chunk_cache, pcol, rg, rows_in_rg)?;
let is_present = chunk.get_bool(row_in_rg)?.unwrap_or(false);
if !is_present {
return Ok(None);
}
true
} else {
false
};
let mut map = BTreeMap::new();
for g in &schema.dict_groups {
if !proj.selects_any_of(&g.field_names) {
continue;
}
let chunk = table.get_chunk(backing, chunk_cache, g.col_id, rg, rows_in_rg)?;
let id = chunk.get_u32(row_in_rg)?.unwrap_or(0);
if id == 0 {
continue;
}
let dict_row = (id - 1) as usize;
match &dicts.dicts[g.dict_id as usize] {
DictReader::Struct {
table: dict_table,
schema: dict_schema,
} => {
let (d_rg, d_row, d_rows) = dict_table.row_group_of(dict_row);
if let Some(sub_map) = read_struct_row(
backing,
dict_table,
dicts,
chunk_cache,
&dict_schema.root,
d_rg,
d_row,
d_rows,
proj,
)? {
for (k, v) in sub_map {
map.insert(k, v);
}
}
}
_ => {
return Err(ReaderError::Corrupt(
"DictGroup does not reference a StructDict".into(),
));
}
}
}
for f in &schema.fields {
let Some(child_proj) = proj.child(&f.name) else {
continue;
};
if let Some(val) = read_column_value(
backing,
table,
dicts,
chunk_cache,
&f.col_type,
rg,
row_in_rg,
rows_in_rg,
child_proj,
)? {
map.insert(f.name.clone(), val);
}
}
if schema.nullable && !explicit_present && map.is_empty() {
Ok(None)
} else {
Ok(Some(map))
}
}
#[allow(clippy::too_many_arguments)]
fn read_column_value(
backing: &Backing<'_>,
table: &ColumnTableReader,
dicts: &DictTablesReader,
chunk_cache: &ChunkCache,
col_type: &ColumnType,
rg: u32,
row_in_rg: usize,
rows_in_rg: usize,
proj: &ProjectionNode,
) -> Result<Option<Value>> {
match col_type {
ColumnType::Primitive { col_id, .. } | ColumnType::Dynamic { col_id, .. } => {
let chunk = table.get_chunk(backing, chunk_cache, *col_id, rg, rows_in_rg)?;
chunk.get_value(row_in_rg)
}
ColumnType::DictRef {
dict_id, col_id, ..
} => {
let chunk = table.get_chunk(backing, chunk_cache, *col_id, rg, rows_in_rg)?;
let id = chunk.get_u32(row_in_rg)?.unwrap_or(0);
if id == 0 {
return Ok(None);
}
read_dict_entry(
backing,
dicts,
chunk_cache,
*dict_id,
(id - 1) as usize,
proj,
)
}
ColumnType::Struct(s) => {
let opt = read_struct_row(
backing,
table,
dicts,
chunk_cache,
s,
rg,
row_in_rg,
rows_in_rg,
proj,
)?;
Ok(opt.map(Value::Map))
}
ColumnType::ShreddedMap {
nullable,
presence_col,
overflow_col,
entries,
} => {
let explicit_present = if let Some(pcol) = presence_col {
let chunk = table.get_chunk(backing, chunk_cache, *pcol, rg, rows_in_rg)?;
let present = chunk.get_bool(row_in_rg)?.unwrap_or(false);
if !present {
return Ok(None);
}
true
} else {
false
};
let mut map = BTreeMap::new();
for e in entries {
let Some(child_proj) = proj.child(&e.key) else {
continue;
};
if let Some(v) = read_column_value(
backing,
table,
dicts,
chunk_cache,
&e.value_type,
rg,
row_in_rg,
rows_in_rg,
child_proj,
)? {
map.insert(e.key.clone(), v);
}
}
if let Some(ocol) = overflow_col {
let need_overflow = match proj {
ProjectionNode::All => true,
ProjectionNode::Fields(req) => {
req.keys().any(|k| !entries.iter().any(|e| e.key == *k))
}
};
if need_overflow {
let chunk = table.get_chunk(backing, chunk_cache, *ocol, rg, rows_in_rg)?;
if let Some(Value::Map(extra)) = chunk.get_value(row_in_rg)? {
for (k, v) in extra {
if proj.child(&k).is_some() {
map.insert(k, v);
}
}
}
}
}
if *nullable && !explicit_present && map.is_empty() {
Ok(None)
} else {
Ok(Some(Value::Map(map)))
}
}
ColumnType::List {
offsets_col,
elem_type,
..
} => {
let off_chunk = table.get_chunk(backing, chunk_cache, *offsets_col, rg, rows_in_rg)?;
let Some((start, len, total_elems)) =
off_chunk.list_range_in_rg(row_in_rg, rows_in_rg)?
else {
return Ok(None);
};
let mut arr = Vec::with_capacity(len);
for elem_idx in start..start + len {
let item = read_column_value(
backing,
table,
dicts,
chunk_cache,
elem_type,
rg,
elem_idx,
total_elems,
proj,
)?
.unwrap_or(Value::Null);
arr.push(item);
}
Ok(Some(Value::Array(arr)))
}
}
}
fn read_dict_entry(
backing: &Backing<'_>,
dicts: &DictTablesReader,
chunk_cache: &ChunkCache,
dict_id: u16,
entry_idx: usize,
proj: &ProjectionNode,
) -> Result<Option<Value>> {
match &dicts.dicts[dict_id as usize] {
DictReader::Flat(flat) => Ok(Some(flat.get(backing, entry_idx)?)),
DictReader::Struct { table, schema } => {
let (rg, row_in_rg, rows_in_rg) = table.row_group_of(entry_idx);
let opt = read_struct_row(
backing,
table,
dicts,
chunk_cache,
&schema.root,
rg,
row_in_rg,
rows_in_rg,
proj,
)?;
Ok(opt.map(Value::Map))
}
DictReader::List(list) => {
let elem_ids = list.get_elem_ids(backing, entry_idx)?;
let mut arr = Vec::with_capacity(elem_ids.len());
for eid in elem_ids {
if eid == 0 {
arr.push(Value::Null);
} else if let Some(v) = read_dict_entry(
backing,
dicts,
chunk_cache,
list.elem_dict_id,
(eid - 1) as usize,
proj,
)? {
arr.push(v);
}
}
Ok(Some(Value::Array(arr)))
}
}
}