use std::cmp::Ordering;
use std::sync::Arc;
use relate_core::Value;
use crate::row::{Row, RowNames};
pub(crate) const CHUNK_ROWS: usize = 512;
#[derive(Clone, Debug, Default)]
pub(crate) struct NullBitmap {
words: Vec<u64>,
len: usize,
}
impl NullBitmap {
pub(super) fn new(len: usize) -> Self {
Self {
words: vec![0; len.div_ceil(u64::BITS as usize)],
len,
}
}
pub(crate) fn get(&self, row: usize) -> bool {
assert!(
row < self.len,
"null bit read for row {row} of {len}",
len = self.len
);
self.words[row / u64::BITS as usize] & (1 << (row % u64::BITS as usize)) != 0
}
pub(super) fn set(&mut self, row: usize) {
assert!(
row < self.len,
"null bit set for row {row} of {len}",
len = self.len
);
self.words[row / u64::BITS as usize] |= 1 << (row % u64::BITS as usize);
}
fn len(&self) -> usize {
self.len
}
}
#[derive(Clone, Debug)]
pub(crate) struct ColumnZone {
null_present: bool,
min_max: Option<(Value, Value)>,
}
impl ColumnZone {
pub(crate) fn null_present(&self) -> bool {
self.null_present
}
pub(crate) fn min_max(&self) -> Option<(&Value, &Value)> {
self.min_max.as_ref().map(|(min, max)| (min, max))
}
}
#[derive(Clone, Debug)]
pub(crate) enum ColumnData {
Int(Vec<i64>),
Float(Vec<f64>),
Utf8(Vec<Arc<str>>),
Bool(Vec<bool>),
Value(Vec<Value>),
}
impl ColumnData {
fn len(&self) -> usize {
match self {
ColumnData::Int(ints) => ints.len(),
ColumnData::Float(floats) => floats.len(),
ColumnData::Utf8(strings) => strings.len(),
ColumnData::Bool(bools) => bools.len(),
ColumnData::Value(values) => values.len(),
}
}
}
#[derive(Clone, Debug)]
pub(crate) struct Column {
nulls: NullBitmap,
data: ColumnData,
zone: ColumnZone,
}
impl Column {
pub(super) fn from_parts(nulls: NullBitmap, data: ColumnData) -> Column {
assert_eq!(
nulls.len(),
data.len(),
"a column's bitmap and buffer agree in length"
);
let zone = zone_of(&nulls, &data);
Column { nulls, data, zone }
}
pub(crate) fn zone(&self) -> &ColumnZone {
&self.zone
}
pub(crate) fn value_at(&self, row: usize) -> Value {
if self.nulls.get(row) {
return Value::Null;
}
match &self.data {
ColumnData::Int(ints) => Value::Int(ints[row]),
ColumnData::Float(floats) => Value::Float(floats[row]),
ColumnData::Utf8(strings) => Value::String(Arc::clone(&strings[row])),
ColumnData::Bool(bools) => Value::Bool(bools[row]),
ColumnData::Value(values) => values[row].clone(),
}
}
pub(crate) fn is_null(&self, row: usize) -> bool {
self.nulls.get(row)
}
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) fn data(&self) -> &ColumnData {
&self.data
}
pub(crate) fn len(&self) -> usize {
self.nulls.len()
}
pub(crate) fn from_values(values: &[Value]) -> Column {
let refs: Vec<&Value> = values.iter().collect();
encode_column(&refs)
}
pub(crate) fn retain_rows(&self, keep: &[usize]) -> Column {
let mut nulls = NullBitmap::new(keep.len());
let data = match &self.data {
ColumnData::Int(ints) => ColumnData::Int(keep.iter().map(|&row| ints[row]).collect()),
ColumnData::Float(floats) => {
ColumnData::Float(keep.iter().map(|&row| floats[row]).collect())
}
ColumnData::Utf8(strings) => {
ColumnData::Utf8(keep.iter().map(|&row| Arc::clone(&strings[row])).collect())
}
ColumnData::Bool(bools) => {
ColumnData::Bool(keep.iter().map(|&row| bools[row]).collect())
}
ColumnData::Value(values) => {
ColumnData::Value(keep.iter().map(|&row| values[row].clone()).collect())
}
};
for (kept, &row) in keep.iter().enumerate() {
if self.nulls.get(row) {
nulls.set(kept);
}
}
Column::from_parts(nulls, data)
}
}
#[derive(Debug)]
pub(super) enum TypedSlot {
Bool(bool),
Int(i64),
Float(f64),
Utf8(Arc<str>),
}
impl TypedSlot {
#[cfg(test)]
pub(super) fn kind(&self) -> TypedKind {
match self {
TypedSlot::Bool(_) => TypedKind::Bool,
TypedSlot::Int(_) => TypedKind::Int,
TypedSlot::Float(_) => TypedKind::Float,
TypedSlot::Utf8(_) => TypedKind::Utf8,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum TypedKind {
Bool,
Int,
Float,
Utf8,
}
pub(super) fn typed_slot(value: &Value) -> Option<TypedSlot> {
match value {
Value::Bool(b) => Some(TypedSlot::Bool(*b)),
Value::Int(i) => Some(TypedSlot::Int(*i)),
Value::Float(f) => Some(TypedSlot::Float(*f)),
Value::String(s) => Some(TypedSlot::Utf8(Arc::clone(s))),
_ => None,
}
}
pub(super) fn typed_kind(value: &Value) -> Option<TypedKind> {
match value {
Value::Bool(_) => Some(TypedKind::Bool),
Value::Int(_) => Some(TypedKind::Int),
Value::Float(_) => Some(TypedKind::Float),
Value::String(_) => Some(TypedKind::Utf8),
_ => None,
}
}
fn classify(values: &[&Value]) -> Option<TypedKind> {
let mut claimed = None;
for value in values {
if value.is_null() {
continue;
}
let kind = typed_kind(value)?;
match claimed {
None => claimed = Some(kind),
Some(claimed) if claimed == kind => {}
Some(_) => return None,
}
}
claimed
}
#[derive(Debug)]
enum TypedBuffer {
Bool(Vec<bool>),
Int(Vec<i64>),
Float(Vec<f64>),
Utf8(Vec<Arc<str>>),
}
impl TypedBuffer {
fn of(kind: TypedKind, capacity: usize) -> Self {
match kind {
TypedKind::Bool => TypedBuffer::Bool(Vec::with_capacity(capacity)),
TypedKind::Int => TypedBuffer::Int(Vec::with_capacity(capacity)),
TypedKind::Float => TypedBuffer::Float(Vec::with_capacity(capacity)),
TypedKind::Utf8 => TypedBuffer::Utf8(Vec::with_capacity(capacity)),
}
}
fn push(&mut self, slot: TypedSlot) {
match (self, slot) {
(TypedBuffer::Bool(buffer), TypedSlot::Bool(b)) => buffer.push(b),
(TypedBuffer::Int(buffer), TypedSlot::Int(i)) => buffer.push(i),
(TypedBuffer::Float(buffer), TypedSlot::Float(f)) => buffer.push(f),
(TypedBuffer::Utf8(buffer), TypedSlot::Utf8(s)) => buffer.push(s),
(buffer, slot) => panic!(
"internal: {buffer:?} received a {slot:?} slot; classify and encode disagree"
),
}
}
fn push_null(&mut self) {
match self {
TypedBuffer::Bool(buffer) => buffer.push(false),
TypedBuffer::Int(buffer) => buffer.push(0),
TypedBuffer::Float(buffer) => buffer.push(0.0),
TypedBuffer::Utf8(buffer) => buffer.push(Arc::from("")),
}
}
fn finish(self) -> ColumnData {
match self {
TypedBuffer::Bool(buffer) => ColumnData::Bool(buffer),
TypedBuffer::Int(buffer) => ColumnData::Int(buffer),
TypedBuffer::Float(buffer) => ColumnData::Float(buffer),
TypedBuffer::Utf8(buffer) => ColumnData::Utf8(buffer),
}
}
}
fn fold_bounds<T: Clone + PartialOrd<T>>(slots: impl Iterator<Item = Option<T>>) -> Option<(T, T)> {
let mut bounds: Option<(T, T)> = None;
for slot in slots {
let Some(value) = slot else { continue };
value.partial_cmp(&value)?;
match &mut bounds {
None => bounds = Some((value.clone(), value)),
Some((min, max)) => {
if value.partial_cmp(min) == Some(Ordering::Less) {
*min = value.clone();
} else if value.partial_cmp(max) == Some(Ordering::Greater) {
*max = value;
}
}
}
}
bounds
}
fn slots<'a, T: Clone>(
nulls: &'a NullBitmap,
buffer: &'a [T],
) -> impl Iterator<Item = Option<T>> + 'a {
buffer
.iter()
.enumerate()
.map(|(row, value)| (!nulls.get(row)).then(|| value.clone()))
}
fn zone_of(nulls: &NullBitmap, data: &ColumnData) -> ColumnZone {
let null_present = nulls.words.iter().any(|&word| word != 0);
let min_max = match data {
ColumnData::Int(ints) => {
fold_bounds(slots(nulls, ints)).map(|(min, max)| (Value::Int(min), Value::Int(max)))
}
ColumnData::Float(floats) => fold_bounds(slots(nulls, floats))
.map(|(min, max)| (Value::Float(min), Value::Float(max))),
ColumnData::Utf8(strings) => fold_bounds(slots(nulls, strings))
.map(|(min, max)| (Value::String(min), Value::String(max))),
ColumnData::Bool(bools) => {
fold_bounds(slots(nulls, bools)).map(|(min, max)| (Value::Bool(min), Value::Bool(max)))
}
ColumnData::Value(_) => None,
};
ColumnZone {
null_present,
min_max,
}
}
pub(crate) fn encode_column(values: &[&Value]) -> Column {
let mut nulls = NullBitmap::new(values.len());
let data = match classify(values) {
Some(kind) => {
let mut buffer = TypedBuffer::of(kind, values.len());
for (row, value) in values.iter().enumerate() {
let slot = match typed_slot(value) {
Some(slot) => slot,
None => {
assert!(
value.is_null(),
"internal: classify() proved every untyped value is null"
);
nulls.set(row);
buffer.push_null();
continue;
}
};
buffer.push(slot);
}
buffer.finish()
}
None => ColumnData::Value(
values
.iter()
.enumerate()
.map(|(row, value)| {
if value.is_null() {
nulls.set(row);
}
(*value).clone()
})
.collect(),
),
};
Column::from_parts(nulls, data)
}
pub(crate) struct Chunk {
names: RowNames,
columns: Vec<Column>,
rows: usize,
}
impl Chunk {
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) fn from_rows(rows: &[Row]) -> Self {
let Some(first) = rows.first() else {
return Self {
names: RowNames::new(&[]),
columns: Vec::new(),
rows: 0,
};
};
let names: Vec<String> = first.keys().cloned().collect();
for (index, row) in rows.iter().enumerate().skip(1) {
assert!(
row.len() == names.len()
&& row
.keys()
.zip(&names)
.all(|(name, expected)| name == expected),
"chunk row {index} diverges from the batch's schema"
);
}
let columns = (0..names.len())
.map(|slot| {
let values: Vec<&Value> = rows.iter().map(|row| &row.values()[slot]).collect();
encode_column(&values)
})
.collect();
Self {
names: RowNames::new(&names),
columns,
rows: rows.len(),
}
}
pub(crate) fn to_rows(&self) -> Vec<Row> {
(0..self.rows)
.map(|row| {
let values = self
.columns
.iter()
.map(|column| column.value_at(row))
.collect();
Row::from_names(&self.names, values)
})
.collect()
}
pub(crate) fn len(&self) -> usize {
self.rows
}
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) fn is_empty(&self) -> bool {
self.rows == 0
}
pub(crate) fn column(&self, slot: usize) -> &Column {
&self.columns[slot]
}
pub(crate) fn from_columns(names: &[String], columns: Vec<Column>) -> Self {
let rows = columns.first().map_or(0, Column::len);
assert!(
names.len() == columns.len() && columns.iter().all(|c| c.len() == rows),
"a chunk's names and columns agree in count and every column in length"
);
Self {
names: RowNames::new(names),
rows,
columns,
}
}
pub(crate) fn retain_rows(&self, keep: &[usize]) -> Self {
Self {
names: self.names.clone(),
columns: self.columns.iter().map(|c| c.retain_rows(keep)).collect(),
rows: keep.len(),
}
}
pub(crate) fn select_columns(self, slots: &[usize]) -> Self {
let names: Vec<String> = slots
.iter()
.map(|&slot| self.names.names()[slot].clone())
.collect();
let mut by_slot: Vec<Option<Column>> = self.columns.into_iter().map(Some).collect();
let columns = slots
.iter()
.map(|&slot| {
by_slot[slot]
.take()
.expect("select_columns slots are in range and distinct")
})
.collect();
Self {
names: RowNames::new(&names),
columns,
rows: self.rows,
}
}
}