1use std::hash::Hasher;
13
14use crate::value::{Date, Decimal, Value};
15
16const NULL: u32 = u32::MAX;
17
18#[derive(Default)]
21struct FxHasher(u64);
22
23impl Hasher for FxHasher {
24 fn write(&mut self, bytes: &[u8]) {
25 const K: u64 = 0x51_7c_c1_b7_27_22_0a_95;
26 let mut chunks = bytes.chunks_exact(8);
27 for c in &mut chunks {
28 self.0 = (self.0.rotate_left(5) ^ u64::from_le_bytes(c.try_into().unwrap_or_default())).wrapping_mul(K);
29 }
30 for &b in chunks.remainder() {
31 self.0 = (self.0.rotate_left(5) ^ b as u64).wrapping_mul(K);
32 }
33 }
34
35 fn finish(&self) -> u64 {
36 self.0
37 }
38}
39
40
41fn hash_text(s: &str) -> u64 {
44 let mut h = FxHasher::default();
45 h.write(s.as_bytes());
46 let mut x = h.finish() ^ s.len() as u64;
47 x = (x ^ (x >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
48 x = (x ^ (x >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
49 x ^ (x >> 31)
50}
51
52const TEXT_BLOCK: usize = 1 << 20;
54
55#[derive(Clone, Debug, Default)]
60struct Words {
61 blocks: Vec<String>,
62 spans: Chunked<(u32, u32, u32)>,
64 index: hashbrown::HashTable<u32>,
65}
66
67impl Words {
68 fn len(&self) -> usize {
69 self.spans.len()
70 }
71
72 fn get(&self, code: u32) -> Option<&str> {
73 let &(block, start, end) = self.spans.get(code as usize)?;
74 self.blocks.get(block as usize)?.get(start as usize..end as usize)
75 }
76
77 fn iter(&self) -> impl Iterator<Item = &str> {
78 self.spans.iter().map(|&(b, s, e)| &self.blocks[b as usize][s as usize..e as usize])
79 }
80
81 fn bytes(&self) -> usize {
82 self.blocks.iter().map(String::capacity).sum::<usize>() + self.spans.len() * 12 + self.index.capacity() * 5
83 }
84
85 fn intern(&mut self, s: &str) -> u32 {
87 let hash = hash_text(s);
88 let Self { blocks, spans, index } = self;
89 let found = index.find(hash, |&c| {
90 let (b, st, e) = *spans.get(c as usize).unwrap_or(&(0, 0, 0));
91 blocks[b as usize].get(st as usize..e as usize) == Some(s)
92 });
93 if let Some(&code) = found {
94 return code;
95 }
96 let fits = blocks.last().is_some_and(|b| b.capacity() - b.len() >= s.len());
97 if !fits {
98 blocks.push(String::with_capacity(TEXT_BLOCK.max(s.len())));
99 }
100 let block = blocks.len() - 1;
101 let last = &mut blocks[block];
102 let start = last.len();
103 last.push_str(s);
104 let code = spans.len() as u32;
105 spans.push((block as u32, start as u32, last.len() as u32));
106 let (blocks, spans) = (&*blocks, &*spans);
107 index.insert_unique(hash, code, |&c| {
108 let (b, st, e) = *spans.get(c as usize).unwrap_or(&(0, 0, 0));
109 hash_text(&blocks[b as usize][st as usize..e as usize])
110 });
111 code
112 }
113}
114
115#[derive(Clone, Debug)]
119struct Chunked<T> {
120 chunks: Vec<Vec<T>>,
121 len: usize,
122}
123
124const CHUNK: usize = 1 << 16;
125
126impl<T> Default for Chunked<T> {
127 fn default() -> Self {
128 Self { chunks: Vec::new(), len: 0 }
129 }
130}
131
132impl<T: Copy> Chunked<T> {
133 fn filled(value: T, n: usize) -> Self {
135 let mut c = Self::default();
136 for _ in 0..n {
137 c.push(value);
138 }
139 c
140 }
141
142 fn push(&mut self, value: T) {
143 match self.chunks.last_mut() {
145 Some(last) if last.len() < CHUNK => last.push(value),
146 _ => {
147 let mut chunk = Vec::with_capacity(if self.chunks.is_empty() { 0 } else { CHUNK });
148 chunk.push(value);
149 self.chunks.push(chunk);
150 }
151 }
152 self.len += 1;
153 }
154
155 fn get(&self, i: usize) -> Option<&T> {
156 self.chunks.get(i / CHUNK)?.get(i % CHUNK)
157 }
158
159 fn len(&self) -> usize {
160 self.len
161 }
162
163 fn iter(&self) -> impl Iterator<Item = &T> {
164 self.chunks.iter().flatten()
165 }
166
167 fn append(&mut self, other: Chunked<T>) {
170 if self.len % CHUNK == 0 {
171 self.len += other.len;
172 self.chunks.extend(other.chunks);
173 } else {
174 for chunk in other.chunks {
175 for v in chunk {
176 self.push(v);
177 }
178 }
179 }
180 }
181}
182
183impl<T: Copy> FromIterator<T> for Chunked<T> {
184 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
185 let mut c = Self::default();
186 for v in iter {
187 c.push(v);
188 }
189 c
190 }
191}
192
193#[derive(Clone, Debug, Default)]
195struct Nulls(Vec<u64>);
196
197impl Nulls {
198 fn set(&mut self, row: usize) {
199 let word = row / 64;
200 if self.0.len() <= word {
201 self.0.resize(word + 1, 0);
202 }
203 self.0[word] |= 1 << (row % 64);
204 }
205
206 fn is(&self, row: usize) -> bool {
207 self.0.get(row / 64).is_some_and(|w| (w >> (row % 64)) & 1 == 1)
208 }
209
210 fn first(row: usize) -> Self {
212 let mut n = Self::default();
213 for r in 0..row {
214 n.set(r);
215 }
216 n
217 }
218
219 fn bytes(&self) -> usize {
220 self.0.len() * 8
221 }
222
223 fn append(&mut self, other: &Nulls, base: usize, len: usize) {
225 if other.0.is_empty() {
226 return;
227 }
228 if base % 64 == 0 {
229 self.0.resize(base / 64, 0);
231 self.0.extend_from_slice(&other.0);
232 } else {
233 for r in 0..len {
234 if other.is(r) {
235 self.set(base + r);
236 }
237 }
238 }
239 }
240}
241
242#[derive(Clone, Debug)]
243enum Column {
244 Empty,
246 Bool(Vec<Option<bool>>),
247 Int32 { values: Chunked<i32>, nulls: Nulls },
249 Int { values: Chunked<i64>, nulls: Nulls },
250 Float { values: Chunked<f64>, nulls: Nulls },
251 Decimal(Vec<Option<Decimal>>),
252 Date(Vec<Option<Date>>),
253 Text { words: Words, codes: Chunked<u32> },
255 Any(Vec<Value>),
257}
258
259#[derive(Clone, Debug, Default)]
261pub(crate) struct ColumnStore {
262 columns: Vec<Column>,
263 len: usize,
264}
265
266impl ColumnStore {
267 pub(crate) fn new(width: usize) -> Self {
268 Self { columns: vec![Column::Empty; width], len: 0 }
269 }
270
271 pub(crate) fn width(&self) -> usize {
272 self.columns.len()
273 }
274
275 pub(crate) fn push(&mut self, values: Vec<Value>) -> u32 {
277 let row = self.len;
278 for (col, value) in values.into_iter().enumerate().take(self.columns.len()) {
279 push_value(&mut self.columns[col], row, value);
280 }
281 for column in &mut self.columns {
283 if column_len(column) < row + 1 {
284 push_value(column, row, Value::Null);
285 }
286 }
287 self.len += 1;
288 row as u32
289 }
290
291 pub(crate) fn get(&self, row: u32, col: usize) -> Value {
293 let r = row as usize;
294 match self.columns.get(col) {
295 None | Some(Column::Empty) => Value::Null,
296 Some(Column::Bool(v)) => v.get(r).copied().flatten().map_or(Value::Null, Value::Bool),
297 Some(Column::Int32 { values, nulls }) => match values.get(r) {
298 Some(&v) if !nulls.is(r) => Value::Int(v as i64),
299 _ => Value::Null,
300 },
301 Some(Column::Int { values, nulls }) => match values.get(r) {
302 Some(&v) if !nulls.is(r) => Value::Int(v),
303 _ => Value::Null,
304 },
305 Some(Column::Float { values, nulls }) => match values.get(r) {
306 Some(&v) if !nulls.is(r) => Value::Float(v),
307 _ => Value::Null,
308 },
309 Some(Column::Decimal(v)) => v.get(r).copied().flatten().map_or(Value::Null, Value::Decimal),
310 Some(Column::Date(v)) => v.get(r).copied().flatten().map_or(Value::Null, Value::Date),
311 Some(Column::Text { words, codes, .. }) => match codes.get(r) {
312 Some(&c) if c != NULL => words.get(c).map_or(Value::Null, |w| Value::String(w.to_string())),
313 _ => Value::Null,
314 },
315 Some(Column::Any(v)) => v.get(r).cloned().unwrap_or_default(),
316 }
317 }
318
319 pub(crate) fn text_ranks(&self, col: usize) -> Option<Vec<u32>> {
323 let Some(Column::Text { words, .. }) = self.columns.get(col) else { return None };
324 let lower: Vec<String> = words.iter().map(str::to_lowercase).collect();
325 let mut order: Vec<u32> = (0..words.len() as u32).collect();
326 order.sort_by(|&a, &b| lower[a as usize].cmp(&lower[b as usize]));
327 let mut ranks = vec![0; words.len()];
328 let mut rank = 0;
329 for (i, &code) in order.iter().enumerate() {
330 if i > 0 && lower[code as usize] != lower[order[i - 1] as usize] {
331 rank = i as u32;
332 }
333 ranks[code as usize] = rank;
334 }
335 Some(ranks)
336 }
337
338 pub(crate) fn sort_key(&self, row: u32, col: usize, ranks: Option<&[u32]>) -> SortKey {
340 let r = row as usize;
341 match (self.columns.get(col), ranks) {
342 (Some(Column::Text { codes, .. }), Some(ranks)) => match codes.get(r) {
343 Some(&code) if code != NULL => SortKey::Text { rank: ranks[code as usize], code },
344 _ => SortKey::Null,
345 },
346 (Some(Column::Int32 { values, nulls }), _) if !nulls.is(r) => values.get(r).map_or(SortKey::Null, |&v| SortKey::Int(v as i64)),
347 (Some(Column::Int { values, nulls }), _) if !nulls.is(r) => values.get(r).map_or(SortKey::Null, |&v| SortKey::Int(v)),
348 (Some(Column::Float { values, nulls }), _) if !nulls.is(r) => values.get(r).map_or(SortKey::Null, |&v| SortKey::Float(v)),
349 _ => SortKey::of(self.get(row, col)),
350 }
351 }
352
353 pub(crate) fn word(&self, col: usize, code: u32) -> &str {
355 match self.columns.get(col) {
356 Some(Column::Text { words, .. }) => words.get(code).unwrap_or(""),
357 _ => "",
358 }
359 }
360
361 pub(crate) fn row(&self, row: u32) -> Vec<Value> {
363 (0..self.columns.len()).map(|c| self.get(row, c)).collect()
364 }
365
366 pub fn approx_bytes(&self) -> usize {
368 self.columns
369 .iter()
370 .map(|c| match c {
371 Column::Empty => 0,
372 Column::Bool(v) => v.len() * 2,
373 Column::Int32 { values, nulls } => values.len() * 4 + nulls.bytes(),
374 Column::Int { values, nulls } => values.len() * 8 + nulls.bytes(),
375 Column::Float { values, nulls } => values.len() * 8 + nulls.bytes(),
376 Column::Decimal(v) => v.len() * std::mem::size_of::<Option<Decimal>>(),
377 Column::Date(v) => v.len() * std::mem::size_of::<Option<Date>>(),
378 Column::Text { words, codes } => codes.len() * 4 + words.bytes(),
379 Column::Any(v) => v.len() * std::mem::size_of::<Value>(),
380 })
381 .sum()
382 }
383}
384
385impl ColumnStore {
386 pub(crate) fn len(&self) -> usize {
387 self.len
388 }
389
390 pub(crate) fn spread(self, data: &[bool]) -> Self {
393 let mut given = self.columns.into_iter();
394 let columns = data.iter().map(|&d| if d { given.next().unwrap_or(Column::Empty) } else { Column::Empty }).collect();
395 Self { columns, len: self.len }
396 }
397
398 pub(crate) fn append(&mut self, other: ColumnStore) {
403 let base = self.len;
404 let len = other.len;
405 for (mine, theirs) in self.columns.iter_mut().zip(other.columns) {
406 match (&mut *mine, theirs) {
407 (_, Column::Empty) => {
408 if !matches!(mine, Column::Empty) {
410 for r in 0..len {
411 push_value(mine, base + r, Value::Null);
412 }
413 }
414 }
415 (Column::Int32 { values, nulls }, Column::Int32 { values: v, nulls: n }) => {
416 nulls.append(&n, base, len);
417 values.append(v);
418 }
419 (Column::Int { values, nulls }, Column::Int { values: v, nulls: n }) => {
420 nulls.append(&n, base, len);
421 values.append(v);
422 }
423 (Column::Float { values, nulls }, Column::Float { values: v, nulls: n }) => {
424 nulls.append(&n, base, len);
425 values.append(v);
426 }
427 (Column::Text { words, codes }, Column::Text { words: w, codes: mut k }) => {
428 let map: Vec<u32> = w.iter().map(|word| words.intern(word)).collect();
430 for chunk in &mut k.chunks {
431 for code in chunk.iter_mut() {
432 if *code != NULL {
433 *code = map[*code as usize];
434 }
435 }
436 }
437 codes.append(k);
438 }
439 (column, theirs) => {
441 let single = ColumnStore { columns: vec![theirs], len };
442 for r in 0..len {
443 push_value(column, base + r, single.get(r as u32, 0));
444 }
445 }
446 }
447 }
448 self.len += len;
449 }
450}
451
452#[derive(Clone, Debug, Default)]
470pub struct RowBatch {
471 store: ColumnStore,
472 col: usize,
474}
475
476impl RowBatch {
477 pub const PART: usize = CHUNK;
480
481 pub fn new(width: usize) -> Self {
483 Self { store: ColumnStore::new(width), col: 0 }
484 }
485
486 pub fn len(&self) -> usize {
488 self.store.len
489 }
490
491 pub fn is_empty(&self) -> bool {
492 self.store.len == 0
493 }
494
495 pub fn width(&self) -> usize {
496 self.store.columns.len()
497 }
498
499 fn put(&mut self, value: Value) -> &mut Self {
500 if let Some(column) = self.store.columns.get_mut(self.col) {
501 push_value(column, self.store.len, value);
502 self.col += 1;
503 }
504 self
505 }
506
507 pub fn int(&mut self, v: i64) -> &mut Self {
509 match self.store.columns.get_mut(self.col) {
510 Some(Column::Int32 { values, .. }) if i32::try_from(v).is_ok() => values.push(v as i32),
511 Some(Column::Int { values, .. }) => values.push(v),
512 _ => return self.put(Value::Int(v)),
513 }
514 self.col += 1;
515 self
516 }
517
518 pub fn float(&mut self, v: f64) -> &mut Self {
520 match self.store.columns.get_mut(self.col) {
521 Some(Column::Float { values, .. }) => values.push(v),
522 _ => return self.put(Value::Float(v)),
523 }
524 self.col += 1;
525 self
526 }
527
528 pub fn bool(&mut self, v: bool) -> &mut Self {
529 self.put(Value::Bool(v))
530 }
531
532 pub fn text(&mut self, s: &str) -> &mut Self {
534 let row = self.store.len;
535 let Some(column) = self.store.columns.get_mut(self.col) else { return self };
536 match column {
537 Column::Text { words, codes } => codes.push(words.intern(s)),
538 other => push_value(other, row, Value::String(s.to_string())),
539 }
540 self.col += 1;
541 self
542 }
543
544 pub fn value(&mut self, v: Value) -> &mut Self {
546 self.put(v)
547 }
548
549 pub fn null(&mut self) -> &mut Self {
550 self.put(Value::Null)
551 }
552
553 pub fn end_row(&mut self) {
555 while self.col < self.store.columns.len() {
556 self.null();
557 }
558 self.col = 0;
559 self.store.len += 1;
560 }
561
562 pub fn push(&mut self, values: Vec<Value>) {
564 for v in values {
565 self.put(v);
566 }
567 self.end_row();
568 }
569
570 pub fn append(&mut self, other: RowBatch) {
572 self.store.append(other.store);
573 }
574
575 pub(crate) fn into_store(self) -> ColumnStore {
576 self.store
577 }
578}
579
580#[derive(Clone, Debug)]
583pub(crate) enum SortKey {
584 Null,
585 Int(i64),
586 Float(f64),
587 Text { rank: u32, code: u32 },
589 Value(Value),
590}
591
592impl SortKey {
593 pub(crate) fn of(value: Value) -> Self {
594 match value {
595 Value::Null => SortKey::Null,
596 Value::Int(i) => SortKey::Int(i),
597 Value::Float(f) => SortKey::Float(f),
598 v => SortKey::Value(v),
599 }
600 }
601
602 pub(crate) fn order(&self, other: &SortKey, store: &ColumnStore, col: usize) -> std::cmp::Ordering {
604 use std::cmp::Ordering;
605 use SortKey::*;
606 match (self, other) {
607 (Null, Null) => Ordering::Equal,
608 (Null, _) => Ordering::Less,
609 (_, Null) => Ordering::Greater,
610 (Int(a), Int(b)) => a.cmp(b),
611 (Float(a), Float(b)) => a.partial_cmp(b).unwrap_or(Ordering::Equal),
612 (Int(a), Float(b)) => (*a as f64).partial_cmp(b).unwrap_or(Ordering::Equal),
613 (Float(a), Int(b)) => a.partial_cmp(&(*b as f64)).unwrap_or(Ordering::Equal),
614 (Text { rank: a, .. }, Text { rank: b, .. }) => a.cmp(b),
615 (a, b) => crate::expr::sort_order(&a.value(store, col), &b.value(store, col)),
616 }
617 }
618
619 pub(crate) fn packed(&self) -> Option<(u8, u64)> {
623 match self {
624 SortKey::Null => Some((0, 0)),
625 SortKey::Int(i) => Some((1, (*i as u64) ^ (1 << 63))),
626 SortKey::Float(f) if !f.is_nan() => {
627 let bits = f.to_bits();
628 Some((2, if bits >> 63 == 1 { !bits } else { bits | (1 << 63) }))
629 }
630 SortKey::Text { rank, .. } => Some((3, *rank as u64)),
631 _ => None,
632 }
633 }
634
635 fn value(&self, store: &ColumnStore, col: usize) -> Value {
636 match self {
637 SortKey::Null => Value::Null,
638 SortKey::Int(i) => Value::Int(*i),
639 SortKey::Float(f) => Value::Float(*f),
640 SortKey::Text { code, .. } => Value::String(store.word(col, *code).to_string()),
641 SortKey::Value(v) => v.clone(),
642 }
643 }
644}
645
646fn column_len(column: &Column) -> usize {
647 match column {
648 Column::Empty => usize::MAX, Column::Bool(v) => v.len(),
650 Column::Int32 { values, .. } => values.len(),
651 Column::Int { values, .. } => values.len(),
652 Column::Float { values, .. } => values.len(),
653 Column::Decimal(v) => v.len(),
654 Column::Date(v) => v.len(),
655 Column::Text { codes, .. } => codes.len(),
656 Column::Any(v) => v.len(),
657 }
658}
659
660fn push_value(column: &mut Column, row: usize, value: Value) {
664 if let Column::Empty = column {
665 if value.is_null() {
666 return;
667 }
668 *column = match &value {
669 Value::Bool(_) => Column::Bool(vec![None; row]),
670 Value::Int(_) => Column::Int32 { values: Chunked::filled(0, row), nulls: Nulls::first(row) },
671 Value::Float(_) => Column::Float { values: Chunked::filled(0.0, row), nulls: Nulls::first(row) },
672 Value::Decimal(_) => Column::Decimal(vec![None; row]),
673 Value::Date(_) => Column::Date(vec![None; row]),
674 Value::String(_) => Column::Text { words: Words::default(), codes: Chunked::filled(NULL, row) },
675 _ => Column::Any(vec![Value::Null; row]),
676 };
677 }
678 let rejected: Option<Value> = match (&mut *column, value) {
680 (Column::Bool(v), Value::Bool(b)) => {
681 v.push(Some(b));
682 None
683 }
684 (Column::Int32 { values, .. }, Value::Int(i)) if i32::try_from(i).is_ok() => {
685 values.push(i as i32);
686 None
687 }
688 (Column::Int32 { values, nulls }, Value::Int(i)) => {
689 let mut wide: Chunked<i64> = values.iter().map(|&v| v as i64).collect();
691 wide.push(i);
692 *column = Column::Int { values: wide, nulls: std::mem::take(nulls) };
693 None
694 }
695 (Column::Int { values, .. }, Value::Int(i)) => {
696 values.push(i);
697 None
698 }
699 (Column::Float { values, .. }, Value::Float(f)) => {
700 values.push(f);
701 None
702 }
703 (Column::Decimal(v), Value::Decimal(d)) => {
704 v.push(Some(d));
705 None
706 }
707 (Column::Date(v), Value::Date(d)) => {
708 v.push(Some(d));
709 None
710 }
711 (Column::Text { words, codes }, Value::String(s)) => {
712 codes.push(words.intern(&s));
713 None
714 }
715 (Column::Text { codes, .. }, Value::Null) => {
716 codes.push(NULL);
717 None
718 }
719 (Column::Any(v), value) => {
720 v.push(value);
721 None
722 }
723 (Column::Bool(v), Value::Null) => {
724 v.push(None);
725 None
726 }
727 (Column::Int32 { values, nulls }, Value::Null) => {
728 nulls.set(values.len());
729 values.push(0);
730 None
731 }
732 (Column::Int { values, nulls }, Value::Null) => {
733 nulls.set(values.len());
734 values.push(0);
735 None
736 }
737 (Column::Float { values, nulls }, Value::Null) => {
738 nulls.set(values.len());
739 values.push(0.0);
740 None
741 }
742 (Column::Decimal(v), Value::Null) => {
743 v.push(None);
744 None
745 }
746 (Column::Date(v), Value::Null) => {
747 v.push(None);
748 None
749 }
750 (Column::Empty, _) => None,
751 (_, other) => Some(other),
752 };
753 if let Some(other) = rejected {
755 let len = column_len(column);
756 let snapshot = ColumnStore { columns: vec![column.clone()], len };
757 let mut all: Vec<Value> = (0..len).map(|r| snapshot.get(r as u32, 0)).collect();
758 all.push(other);
759 *column = Column::Any(all);
760 }
761}
762
763#[cfg(test)]
764mod tests {
765 use super::*;
766
767 #[test]
768 fn the_dictionary_keeps_each_text_once_across_blocks() {
769 let mut words = Words::default();
770 let a = words.intern("São Paulo");
771 assert_eq!(words.intern("São Paulo"), a);
772 let many: Vec<u32> = (0..100_000).map(|i| words.intern(&format!("مرحبا {i} 👍🏽"))).collect();
774 let huge = "x".repeat(TEXT_BLOCK + 10);
775 let h = words.intern(&huge);
776 assert!(words.blocks.len() > 2);
777 assert_eq!(words.get(a), Some("São Paulo"));
778 assert_eq!(words.get(many[54_321]), Some("مرحبا 54321 👍🏽"));
779 assert_eq!(words.get(h), Some(huge.as_str()));
780 assert_eq!(words.intern("مرحبا 99999 👍🏽"), many[99_999]);
781 assert_eq!(words.intern(""), words.intern(""));
782 assert_eq!(words.len(), 100_003);
783 assert_eq!(words.iter().nth(1), Some("مرحبا 0 👍🏽"));
784 }
785}