use std::hash::Hasher;
use crate::value::{Date, Decimal, Value};
const NULL: u32 = u32::MAX;
#[derive(Default)]
struct FxHasher(u64);
impl Hasher for FxHasher {
fn write(&mut self, bytes: &[u8]) {
const K: u64 = 0x51_7c_c1_b7_27_22_0a_95;
let mut chunks = bytes.chunks_exact(8);
for c in &mut chunks {
self.0 = (self.0.rotate_left(5) ^ u64::from_le_bytes(c.try_into().unwrap_or_default())).wrapping_mul(K);
}
for &b in chunks.remainder() {
self.0 = (self.0.rotate_left(5) ^ b as u64).wrapping_mul(K);
}
}
fn finish(&self) -> u64 {
self.0
}
}
fn hash_text(s: &str) -> u64 {
let mut h = FxHasher::default();
h.write(s.as_bytes());
let mut x = h.finish() ^ s.len() as u64;
x = (x ^ (x >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
x = (x ^ (x >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
x ^ (x >> 31)
}
const TEXT_BLOCK: usize = 1 << 20;
#[derive(Clone, Debug, Default)]
struct Words {
blocks: Vec<String>,
spans: Chunked<(u32, u32, u32)>,
index: hashbrown::HashTable<u32>,
}
impl Words {
fn len(&self) -> usize {
self.spans.len()
}
fn get(&self, code: u32) -> Option<&str> {
let &(block, start, end) = self.spans.get(code as usize)?;
self.blocks.get(block as usize)?.get(start as usize..end as usize)
}
fn iter(&self) -> impl Iterator<Item = &str> {
self.spans.iter().map(|&(b, s, e)| &self.blocks[b as usize][s as usize..e as usize])
}
fn bytes(&self) -> usize {
self.blocks.iter().map(String::capacity).sum::<usize>() + self.spans.len() * 12 + self.index.capacity() * 5
}
fn intern(&mut self, s: &str) -> u32 {
let hash = hash_text(s);
let Self { blocks, spans, index } = self;
let found = index.find(hash, |&c| {
let (b, st, e) = *spans.get(c as usize).unwrap_or(&(0, 0, 0));
blocks[b as usize].get(st as usize..e as usize) == Some(s)
});
if let Some(&code) = found {
return code;
}
let fits = blocks.last().is_some_and(|b| b.capacity() - b.len() >= s.len());
if !fits {
blocks.push(String::with_capacity(TEXT_BLOCK.max(s.len())));
}
let block = blocks.len() - 1;
let last = &mut blocks[block];
let start = last.len();
last.push_str(s);
let code = spans.len() as u32;
spans.push((block as u32, start as u32, last.len() as u32));
let (blocks, spans) = (&*blocks, &*spans);
index.insert_unique(hash, code, |&c| {
let (b, st, e) = *spans.get(c as usize).unwrap_or(&(0, 0, 0));
hash_text(&blocks[b as usize][st as usize..e as usize])
});
code
}
}
#[derive(Clone, Debug)]
struct Chunked<T> {
chunks: Vec<Vec<T>>,
len: usize,
}
const CHUNK: usize = 1 << 16;
impl<T> Default for Chunked<T> {
fn default() -> Self {
Self { chunks: Vec::new(), len: 0 }
}
}
impl<T: Copy> Chunked<T> {
fn filled(value: T, n: usize) -> Self {
let mut c = Self::default();
for _ in 0..n {
c.push(value);
}
c
}
fn push(&mut self, value: T) {
match self.chunks.last_mut() {
Some(last) if last.len() < CHUNK => last.push(value),
_ => {
let mut chunk = Vec::with_capacity(if self.chunks.is_empty() { 0 } else { CHUNK });
chunk.push(value);
self.chunks.push(chunk);
}
}
self.len += 1;
}
fn get(&self, i: usize) -> Option<&T> {
self.chunks.get(i / CHUNK)?.get(i % CHUNK)
}
fn len(&self) -> usize {
self.len
}
fn iter(&self) -> impl Iterator<Item = &T> {
self.chunks.iter().flatten()
}
fn append(&mut self, other: Chunked<T>) {
if self.len % CHUNK == 0 {
self.len += other.len;
self.chunks.extend(other.chunks);
} else {
for chunk in other.chunks {
for v in chunk {
self.push(v);
}
}
}
}
}
impl<T: Copy> FromIterator<T> for Chunked<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
let mut c = Self::default();
for v in iter {
c.push(v);
}
c
}
}
#[derive(Clone, Debug, Default)]
struct Nulls(Vec<u64>);
impl Nulls {
fn set(&mut self, row: usize) {
let word = row / 64;
if self.0.len() <= word {
self.0.resize(word + 1, 0);
}
self.0[word] |= 1 << (row % 64);
}
fn is(&self, row: usize) -> bool {
self.0.get(row / 64).is_some_and(|w| (w >> (row % 64)) & 1 == 1)
}
fn first(row: usize) -> Self {
let mut n = Self::default();
for r in 0..row {
n.set(r);
}
n
}
fn bytes(&self) -> usize {
self.0.len() * 8
}
fn append(&mut self, other: &Nulls, base: usize, len: usize) {
if other.0.is_empty() {
return;
}
if base % 64 == 0 {
self.0.resize(base / 64, 0);
self.0.extend_from_slice(&other.0);
} else {
for r in 0..len {
if other.is(r) {
self.set(base + r);
}
}
}
}
}
#[derive(Clone, Debug)]
enum Column {
Empty,
Bool(Vec<Option<bool>>),
Int32 { values: Chunked<i32>, nulls: Nulls },
Int { values: Chunked<i64>, nulls: Nulls },
Float { values: Chunked<f64>, nulls: Nulls },
Decimal(Vec<Option<Decimal>>),
Date(Vec<Option<Date>>),
Text { words: Words, codes: Chunked<u32> },
Any(Vec<Value>),
}
#[derive(Clone, Debug, Default)]
pub(crate) struct ColumnStore {
columns: Vec<Column>,
len: usize,
}
impl ColumnStore {
pub(crate) fn new(width: usize) -> Self {
Self { columns: vec![Column::Empty; width], len: 0 }
}
pub(crate) fn width(&self) -> usize {
self.columns.len()
}
pub(crate) fn push(&mut self, values: Vec<Value>) -> u32 {
let row = self.len;
for (col, value) in values.into_iter().enumerate().take(self.columns.len()) {
push_value(&mut self.columns[col], row, value);
}
for column in &mut self.columns {
if column_len(column) < row + 1 {
push_value(column, row, Value::Null);
}
}
self.len += 1;
row as u32
}
pub(crate) fn get(&self, row: u32, col: usize) -> Value {
let r = row as usize;
match self.columns.get(col) {
None | Some(Column::Empty) => Value::Null,
Some(Column::Bool(v)) => v.get(r).copied().flatten().map_or(Value::Null, Value::Bool),
Some(Column::Int32 { values, nulls }) => match values.get(r) {
Some(&v) if !nulls.is(r) => Value::Int(v as i64),
_ => Value::Null,
},
Some(Column::Int { values, nulls }) => match values.get(r) {
Some(&v) if !nulls.is(r) => Value::Int(v),
_ => Value::Null,
},
Some(Column::Float { values, nulls }) => match values.get(r) {
Some(&v) if !nulls.is(r) => Value::Float(v),
_ => Value::Null,
},
Some(Column::Decimal(v)) => v.get(r).copied().flatten().map_or(Value::Null, Value::Decimal),
Some(Column::Date(v)) => v.get(r).copied().flatten().map_or(Value::Null, Value::Date),
Some(Column::Text { words, codes, .. }) => match codes.get(r) {
Some(&c) if c != NULL => words.get(c).map_or(Value::Null, |w| Value::String(w.to_string())),
_ => Value::Null,
},
Some(Column::Any(v)) => v.get(r).cloned().unwrap_or_default(),
}
}
pub(crate) fn text_ranks(&self, col: usize) -> Option<Vec<u32>> {
let Some(Column::Text { words, .. }) = self.columns.get(col) else { return None };
let lower: Vec<String> = words.iter().map(str::to_lowercase).collect();
let mut order: Vec<u32> = (0..words.len() as u32).collect();
order.sort_by(|&a, &b| lower[a as usize].cmp(&lower[b as usize]));
let mut ranks = vec![0; words.len()];
let mut rank = 0;
for (i, &code) in order.iter().enumerate() {
if i > 0 && lower[code as usize] != lower[order[i - 1] as usize] {
rank = i as u32;
}
ranks[code as usize] = rank;
}
Some(ranks)
}
pub(crate) fn sort_key(&self, row: u32, col: usize, ranks: Option<&[u32]>) -> SortKey {
let r = row as usize;
match (self.columns.get(col), ranks) {
(Some(Column::Text { codes, .. }), Some(ranks)) => match codes.get(r) {
Some(&code) if code != NULL => SortKey::Text { rank: ranks[code as usize], code },
_ => SortKey::Null,
},
(Some(Column::Int32 { values, nulls }), _) if !nulls.is(r) => values.get(r).map_or(SortKey::Null, |&v| SortKey::Int(v as i64)),
(Some(Column::Int { values, nulls }), _) if !nulls.is(r) => values.get(r).map_or(SortKey::Null, |&v| SortKey::Int(v)),
(Some(Column::Float { values, nulls }), _) if !nulls.is(r) => values.get(r).map_or(SortKey::Null, |&v| SortKey::Float(v)),
_ => SortKey::of(self.get(row, col)),
}
}
pub(crate) fn word(&self, col: usize, code: u32) -> &str {
match self.columns.get(col) {
Some(Column::Text { words, .. }) => words.get(code).unwrap_or(""),
_ => "",
}
}
pub(crate) fn row(&self, row: u32) -> Vec<Value> {
(0..self.columns.len()).map(|c| self.get(row, c)).collect()
}
pub fn approx_bytes(&self) -> usize {
self.columns
.iter()
.map(|c| match c {
Column::Empty => 0,
Column::Bool(v) => v.len() * 2,
Column::Int32 { values, nulls } => values.len() * 4 + nulls.bytes(),
Column::Int { values, nulls } => values.len() * 8 + nulls.bytes(),
Column::Float { values, nulls } => values.len() * 8 + nulls.bytes(),
Column::Decimal(v) => v.len() * std::mem::size_of::<Option<Decimal>>(),
Column::Date(v) => v.len() * std::mem::size_of::<Option<Date>>(),
Column::Text { words, codes } => codes.len() * 4 + words.bytes(),
Column::Any(v) => v.len() * std::mem::size_of::<Value>(),
})
.sum()
}
}
impl ColumnStore {
pub(crate) fn len(&self) -> usize {
self.len
}
pub(crate) fn spread(self, data: &[bool]) -> Self {
let mut given = self.columns.into_iter();
let columns = data.iter().map(|&d| if d { given.next().unwrap_or(Column::Empty) } else { Column::Empty }).collect();
Self { columns, len: self.len }
}
pub(crate) fn append(&mut self, other: ColumnStore) {
let base = self.len;
let len = other.len;
for (mine, theirs) in self.columns.iter_mut().zip(other.columns) {
match (&mut *mine, theirs) {
(_, Column::Empty) => {
if !matches!(mine, Column::Empty) {
for r in 0..len {
push_value(mine, base + r, Value::Null);
}
}
}
(Column::Int32 { values, nulls }, Column::Int32 { values: v, nulls: n }) => {
nulls.append(&n, base, len);
values.append(v);
}
(Column::Int { values, nulls }, Column::Int { values: v, nulls: n }) => {
nulls.append(&n, base, len);
values.append(v);
}
(Column::Float { values, nulls }, Column::Float { values: v, nulls: n }) => {
nulls.append(&n, base, len);
values.append(v);
}
(Column::Text { words, codes }, Column::Text { words: w, codes: mut k }) => {
let map: Vec<u32> = w.iter().map(|word| words.intern(word)).collect();
for chunk in &mut k.chunks {
for code in chunk.iter_mut() {
if *code != NULL {
*code = map[*code as usize];
}
}
}
codes.append(k);
}
(column, theirs) => {
let single = ColumnStore { columns: vec![theirs], len };
for r in 0..len {
push_value(column, base + r, single.get(r as u32, 0));
}
}
}
}
self.len += len;
}
}
#[derive(Clone, Debug, Default)]
pub struct RowBatch {
store: ColumnStore,
col: usize,
}
impl RowBatch {
pub const PART: usize = CHUNK;
pub fn new(width: usize) -> Self {
Self { store: ColumnStore::new(width), col: 0 }
}
pub fn len(&self) -> usize {
self.store.len
}
pub fn is_empty(&self) -> bool {
self.store.len == 0
}
pub fn width(&self) -> usize {
self.store.columns.len()
}
fn put(&mut self, value: Value) -> &mut Self {
if let Some(column) = self.store.columns.get_mut(self.col) {
push_value(column, self.store.len, value);
self.col += 1;
}
self
}
pub fn int(&mut self, v: i64) -> &mut Self {
match self.store.columns.get_mut(self.col) {
Some(Column::Int32 { values, .. }) if i32::try_from(v).is_ok() => values.push(v as i32),
Some(Column::Int { values, .. }) => values.push(v),
_ => return self.put(Value::Int(v)),
}
self.col += 1;
self
}
pub fn float(&mut self, v: f64) -> &mut Self {
match self.store.columns.get_mut(self.col) {
Some(Column::Float { values, .. }) => values.push(v),
_ => return self.put(Value::Float(v)),
}
self.col += 1;
self
}
pub fn bool(&mut self, v: bool) -> &mut Self {
self.put(Value::Bool(v))
}
pub fn text(&mut self, s: &str) -> &mut Self {
let row = self.store.len;
let Some(column) = self.store.columns.get_mut(self.col) else { return self };
match column {
Column::Text { words, codes } => codes.push(words.intern(s)),
other => push_value(other, row, Value::String(s.to_string())),
}
self.col += 1;
self
}
pub fn value(&mut self, v: Value) -> &mut Self {
self.put(v)
}
pub fn null(&mut self) -> &mut Self {
self.put(Value::Null)
}
pub fn end_row(&mut self) {
while self.col < self.store.columns.len() {
self.null();
}
self.col = 0;
self.store.len += 1;
}
pub fn push(&mut self, values: Vec<Value>) {
for v in values {
self.put(v);
}
self.end_row();
}
pub fn append(&mut self, other: RowBatch) {
self.store.append(other.store);
}
pub(crate) fn into_store(self) -> ColumnStore {
self.store
}
}
#[derive(Clone, Debug)]
pub(crate) enum SortKey {
Null,
Int(i64),
Float(f64),
Text { rank: u32, code: u32 },
Value(Value),
}
impl SortKey {
pub(crate) fn of(value: Value) -> Self {
match value {
Value::Null => SortKey::Null,
Value::Int(i) => SortKey::Int(i),
Value::Float(f) => SortKey::Float(f),
v => SortKey::Value(v),
}
}
pub(crate) fn order(&self, other: &SortKey, store: &ColumnStore, col: usize) -> std::cmp::Ordering {
use std::cmp::Ordering;
use SortKey::*;
match (self, other) {
(Null, Null) => Ordering::Equal,
(Null, _) => Ordering::Less,
(_, Null) => Ordering::Greater,
(Int(a), Int(b)) => a.cmp(b),
(Float(a), Float(b)) => a.partial_cmp(b).unwrap_or(Ordering::Equal),
(Int(a), Float(b)) => (*a as f64).partial_cmp(b).unwrap_or(Ordering::Equal),
(Float(a), Int(b)) => a.partial_cmp(&(*b as f64)).unwrap_or(Ordering::Equal),
(Text { rank: a, .. }, Text { rank: b, .. }) => a.cmp(b),
(a, b) => crate::expr::sort_order(&a.value(store, col), &b.value(store, col)),
}
}
pub(crate) fn packed(&self) -> Option<(u8, u64)> {
match self {
SortKey::Null => Some((0, 0)),
SortKey::Int(i) => Some((1, (*i as u64) ^ (1 << 63))),
SortKey::Float(f) if !f.is_nan() => {
let bits = f.to_bits();
Some((2, if bits >> 63 == 1 { !bits } else { bits | (1 << 63) }))
}
SortKey::Text { rank, .. } => Some((3, *rank as u64)),
_ => None,
}
}
fn value(&self, store: &ColumnStore, col: usize) -> Value {
match self {
SortKey::Null => Value::Null,
SortKey::Int(i) => Value::Int(*i),
SortKey::Float(f) => Value::Float(*f),
SortKey::Text { code, .. } => Value::String(store.word(col, *code).to_string()),
SortKey::Value(v) => v.clone(),
}
}
}
fn column_len(column: &Column) -> usize {
match column {
Column::Empty => usize::MAX, Column::Bool(v) => v.len(),
Column::Int32 { values, .. } => values.len(),
Column::Int { values, .. } => values.len(),
Column::Float { values, .. } => values.len(),
Column::Decimal(v) => v.len(),
Column::Date(v) => v.len(),
Column::Text { codes, .. } => codes.len(),
Column::Any(v) => v.len(),
}
}
fn push_value(column: &mut Column, row: usize, value: Value) {
if let Column::Empty = column {
if value.is_null() {
return;
}
*column = match &value {
Value::Bool(_) => Column::Bool(vec![None; row]),
Value::Int(_) => Column::Int32 { values: Chunked::filled(0, row), nulls: Nulls::first(row) },
Value::Float(_) => Column::Float { values: Chunked::filled(0.0, row), nulls: Nulls::first(row) },
Value::Decimal(_) => Column::Decimal(vec![None; row]),
Value::Date(_) => Column::Date(vec![None; row]),
Value::String(_) => Column::Text { words: Words::default(), codes: Chunked::filled(NULL, row) },
_ => Column::Any(vec![Value::Null; row]),
};
}
let rejected: Option<Value> = match (&mut *column, value) {
(Column::Bool(v), Value::Bool(b)) => {
v.push(Some(b));
None
}
(Column::Int32 { values, .. }, Value::Int(i)) if i32::try_from(i).is_ok() => {
values.push(i as i32);
None
}
(Column::Int32 { values, nulls }, Value::Int(i)) => {
let mut wide: Chunked<i64> = values.iter().map(|&v| v as i64).collect();
wide.push(i);
*column = Column::Int { values: wide, nulls: std::mem::take(nulls) };
None
}
(Column::Int { values, .. }, Value::Int(i)) => {
values.push(i);
None
}
(Column::Float { values, .. }, Value::Float(f)) => {
values.push(f);
None
}
(Column::Decimal(v), Value::Decimal(d)) => {
v.push(Some(d));
None
}
(Column::Date(v), Value::Date(d)) => {
v.push(Some(d));
None
}
(Column::Text { words, codes }, Value::String(s)) => {
codes.push(words.intern(&s));
None
}
(Column::Text { codes, .. }, Value::Null) => {
codes.push(NULL);
None
}
(Column::Any(v), value) => {
v.push(value);
None
}
(Column::Bool(v), Value::Null) => {
v.push(None);
None
}
(Column::Int32 { values, nulls }, Value::Null) => {
nulls.set(values.len());
values.push(0);
None
}
(Column::Int { values, nulls }, Value::Null) => {
nulls.set(values.len());
values.push(0);
None
}
(Column::Float { values, nulls }, Value::Null) => {
nulls.set(values.len());
values.push(0.0);
None
}
(Column::Decimal(v), Value::Null) => {
v.push(None);
None
}
(Column::Date(v), Value::Null) => {
v.push(None);
None
}
(Column::Empty, _) => None,
(_, other) => Some(other),
};
if let Some(other) = rejected {
let len = column_len(column);
let snapshot = ColumnStore { columns: vec![column.clone()], len };
let mut all: Vec<Value> = (0..len).map(|r| snapshot.get(r as u32, 0)).collect();
all.push(other);
*column = Column::Any(all);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_dictionary_keeps_each_text_once_across_blocks() {
let mut words = Words::default();
let a = words.intern("São Paulo");
assert_eq!(words.intern("São Paulo"), a);
let many: Vec<u32> = (0..100_000).map(|i| words.intern(&format!("مرحبا {i} 👍🏽"))).collect();
let huge = "x".repeat(TEXT_BLOCK + 10);
let h = words.intern(&huge);
assert!(words.blocks.len() > 2);
assert_eq!(words.get(a), Some("São Paulo"));
assert_eq!(words.get(many[54_321]), Some("مرحبا 54321 👍🏽"));
assert_eq!(words.get(h), Some(huge.as_str()));
assert_eq!(words.intern("مرحبا 99999 👍🏽"), many[99_999]);
assert_eq!(words.intern(""), words.intern(""));
assert_eq!(words.len(), 100_003);
assert_eq!(words.iter().nth(1), Some("مرحبا 0 👍🏽"));
}
}