pigeonhole 1.3.2

Embedded, single-file, wide-column store: BigTable's data model with SQLite's deployment model.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
use std::borrow::Cow;
use std::ops::Range;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering::Relaxed};

use pigeonhole_engine::{CellData, FamilyId, TableInfo, ValueRef};

/// A typed view of a value.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub enum Value<'a> {
    /// Opaque bytes.
    Bytes(&'a [u8]),
    /// A signed 64-bit integer (counters).
    I64(i64),
    /// A 64-bit float.
    F64(f64),
    /// A varint-encoded signed integer.
    Varint(i64),
    /// A vector, in a vector family (D303, [`VectorSpec`](crate::VectorSpec)).
    Vector(crate::VectorRef<'a>),
}

/// The value bytes of a stored value: everything after the tag byte.
#[inline]
fn payload(data: &CellData) -> &[u8] {
    data.stored().get(1..).unwrap_or_default()
}

fn typed(data: &CellData) -> Value<'_> {
    typed_value(data.value())
}

/// A decoded stored value as the read API types it (reads, and the change feed's values).
pub(crate) fn typed_value(value: ValueRef<'_>) -> Value<'_> {
    match value {
        ValueRef::Bytes(b) => Value::Bytes(b),
        ValueRef::I64(v) => Value::I64(v),
        ValueRef::F64(v) => Value::F64(v),
        ValueRef::Varint(v) => Value::Varint(v),
        ValueRef::Vector(v) => Value::Vector(crate::VectorRef::new(v)),
        // The engine resolves blob pointers on read; never reached.
        ValueRef::Blob(_) => Value::Bytes(&[]),
    }
}

/// The estimated distinct count of an HLL family's cell (D294).
fn hll_estimate(data: &CellData) -> Option<u64> {
    match data.value() {
        ValueRef::Bytes(b) => pigeonhole_format::hll::estimate(b).ok(),
        _ => None,
    }
}

fn as_f64(data: &CellData) -> Option<f64> {
    match data.value() {
        ValueRef::F64(x) => Some(x),
        _ => None,
    }
}

fn histogram_counts(data: &CellData) -> Option<Vec<u64>> {
    match data.value() {
        ValueRef::Bytes(b) => pigeonhole_format::buckets::histogram_counts(b, None).ok(),
        _ => None,
    }
}

fn quantile(data: &CellData, q: f64) -> Option<f64> {
    match data.value() {
        ValueRef::Bytes(b) => pigeonhole_format::buckets::quantile(b, q),
        _ => None,
    }
}

fn quantiles_count(data: &CellData) -> Option<u64> {
    match data.value() {
        ValueRef::Bytes(b) => pigeonhole_format::buckets::quantiles_count(b).ok(),
        _ => None,
    }
}

fn bloom_contains(data: &CellData, h: u64) -> Option<bool> {
    match data.value() {
        ValueRef::Bytes(b) => pigeonhole_format::bloom::contains(b, h).ok(),
        _ => None,
    }
}

fn bloom_fill(data: &CellData) -> Option<f64> {
    match data.value() {
        ValueRef::Bytes(b) => pigeonhole_format::bloom::fill(b).ok(),
        _ => None,
    }
}

fn sum_f64(data: &CellData) -> Option<f64> {
    match data.value() {
        ValueRef::Bytes(b) => pigeonhole_format::exact::sum_read(b).ok(),
        _ => None,
    }
}

fn mean_var(data: &CellData) -> Option<MeanVar> {
    match data.value() {
        ValueRef::Bytes(b) => pigeonhole_format::exact::mean_var_read(b)
            .ok()
            .map(|r| MeanVar {
                count: r.count,
                mean: r.mean,
                variance: r.variance,
                sample_variance: r.sample_variance,
            }),
        _ => None,
    }
}

/// What a mean-variance cell reads as ([`Aggregation::MeanVar`](crate::Aggregation::MeanVar),
/// D298): each figure is computed exactly from the inputs' count, sum and sum of squares, and
/// rounded once, so the same inputs read the same figures in any order.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MeanVar {
    count: u64,
    mean: f64,
    variance: f64,
    sample_variance: Option<f64>,
}

impl MeanVar {
    /// How many inputs the cell holds.
    pub fn count(&self) -> u64 {
        self.count
    }

    /// Their mean.
    pub fn mean(&self) -> f64 {
        self.mean
    }

    /// Their population variance (divided by the count).
    pub fn variance(&self) -> f64 {
        self.variance
    }

    /// Their sample variance (divided by the count less one); `None` for a single input.
    pub fn sample_variance(&self) -> Option<f64> {
        self.sample_variance
    }
}

fn as_i64(data: &CellData) -> Option<i64> {
    match data.value() {
        ValueRef::I64(v) | ValueRef::Varint(v) => Some(v),
        _ => None,
    }
}

/// A borrowed cell version, tied to the table handle that read it. Reading it allocates
/// nothing; the bytes stay pinned until it drops. [`CellRef::to_owned`] keeps them longer.
///
/// ```
/// use pigeonhole::{Family, Options, Pigeonhole, Value};
///
/// # fn main() -> pigeonhole::Result<()> {
/// # let dir = pigeonhole::doc_support::temp_dir();
/// let db = Pigeonhole::open(dir.join("app.phdb"), Options::default().shards(1))?;
/// let t = db.table("t")?.family("f", Family::default()).create_if_missing()?;
/// t.mutate(b"row").put("f", b"name", b"Ada").put_i64("f", b"age", 36).commit()?;
///
/// let name = t.get(b"row", "f", b"name")?.unwrap();
/// assert_eq!(name.value(), b"Ada");
/// assert_eq!(name.typed(), Value::Bytes(b"Ada"));
/// let age = t.get(b"row", "f", b"age")?.unwrap();
/// assert_eq!(age.as_i64(), Some(36));
/// assert_eq!(age.value(), 36i64.to_le_bytes());
///
/// // Keep a cell past the borrow of the table.
/// let owned = name.to_owned();
/// drop(t);
/// assert_eq!(owned.value(), b"Ada");
/// # db.close()?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct CellRef<'a> {
    data: Cow<'a, CellData>,
}

impl<'a> CellRef<'a> {
    #[inline]
    pub(crate) fn owned(data: CellData) -> Self {
        Self {
            data: Cow::Owned(data),
        }
    }

    pub(crate) fn borrowed(data: &'a CellData) -> Self {
        Self {
            data: Cow::Borrowed(data),
        }
    }

    /// The value bytes (for typed values, their encoding without the tag).
    #[inline]
    pub fn value(&self) -> &[u8] {
        payload(&self.data)
    }

    /// The typed value.
    pub fn typed(&self) -> Value<'_> {
        typed(&self.data)
    }

    /// The value as an `i64`, if it is one.
    pub fn as_i64(&self) -> Option<i64> {
        as_i64(&self.data)
    }

    /// The value as a `u64`: an `i64` value's bits, as a bitwise aggregate family holds them
    /// ([`Aggregation::BitOr`](crate::Aggregation::BitOr), D298); `None` if it isn't one.
    pub fn as_u64(&self) -> Option<u64> {
        as_i64(&self.data).map(|v| v as u64)
    }

    /// The value as an `f64`, if it is one (an `f64` aggregate family's cells are).
    pub fn as_f64(&self) -> Option<f64> {
        as_f64(&self.data)
    }

    /// The value as a vector, if it is one (a vector family's cells are, D303).
    pub fn as_vector(&self) -> Option<crate::VectorRef<'_>> {
        match self.data.value() {
            ValueRef::Vector(v) => Some(crate::VectorRef::new(v)),
            _ => None,
        }
    }

    /// The sum an exact-sum state holds, rounded once to the nearest `f64`, as an exact-sum
    /// family's cells hold ([`Aggregation::SumF64`](crate::Aggregation::SumF64), D298). The
    /// value's shape decides, as for [`hll_estimate`](Self::hll_estimate): `None` unless it
    /// is a well-formed state.
    pub fn sum_f64(&self) -> Option<f64> {
        sum_f64(&self.data)
    }

    /// The count, mean and variance a mean-variance state holds
    /// ([`Aggregation::MeanVar`](crate::Aggregation::MeanVar), D298); `None` unless the value
    /// is a well-formed one.
    pub fn mean_var(&self) -> Option<MeanVar> {
        mean_var(&self.data)
    }

    /// The per-bucket counts a histogram state holds, one per bucket of the family's
    /// [`HistogramParams`](crate::HistogramParams) (D298); `None` unless the value is a
    /// well-formed one.
    pub fn histogram_counts(&self) -> Option<Vec<u64>> {
        histogram_counts(&self.data)
    }

    /// The `q`-quantile (`0 ≤ q ≤ 1`) a quantile sketch holds
    /// ([`Aggregation::Quantiles`](crate::Aggregation::Quantiles), D298): its bucket's
    /// midpoint for the input of rank `⌊q·(n−1)⌋`, within a relative error of 2^-p while
    /// nothing has collapsed. `None` unless the value is a well-formed sketch and `q` is in
    /// range.
    pub fn quantile(&self, q: f64) -> Option<f64> {
        quantile(&self.data, q)
    }

    /// The number of inputs a quantile sketch holds.
    pub fn quantiles_count(&self) -> Option<u64> {
        quantiles_count(&self.data)
    }

    /// Whether a bloom filter ([`Aggregation::Bloom`](crate::Aggregation::Bloom), D298) may
    /// hold the `i64` element `v`: `Some(false)` means certainly not. `None` unless the value
    /// is a well-formed filter.
    pub fn bloom_contains(&self, v: i64) -> Option<bool> {
        bloom_contains(&self.data, pigeonhole_format::hll::hash_i64(v))
    }

    /// [`bloom_contains`](Self::bloom_contains) for a bytes element, as
    /// [`aggregate_bytes`](crate::RowMutation::aggregate_bytes) writes one.
    pub fn bloom_contains_bytes(&self, v: &[u8]) -> Option<bool> {
        bloom_contains(&self.data, pigeonhole_format::hll::hash_bytes(v))
    }

    /// The fraction of a bloom filter's bits set: its false-positive rate is about this to
    /// the power of its hashes.
    pub fn bloom_fill(&self) -> Option<f64> {
        bloom_fill(&self.data)
    }

    /// The set a set family's cell holds ([`Aggregation::Set`](crate::Aggregation::Set),
    /// D298), read in place. `None` unless the value is a well-formed set.
    pub fn as_set(&self) -> Option<crate::SetRef<'_>> {
        match self.data.value() {
            ValueRef::Bytes(b) => crate::SetRef::from_bytes(b),
            _ => None,
        }
    }

    /// The estimated number of distinct elements of an HLL sketch value, as an HLL family's
    /// cells hold ([`Aggregation::Hll`](crate::Aggregation::Hll), D294), about 1.6% standard
    /// error. The value's shape decides, not its family: `None` unless it is a well-formed
    /// sketch.
    pub fn hll_estimate(&self) -> Option<u64> {
        hll_estimate(&self.data)
    }

    /// The version's timestamp (microseconds since the Unix epoch by default).
    pub fn timestamp(&self) -> u64 {
        self.data.timestamp()
    }

    /// An owned handle that can outlive the table borrow (no copy of the value).
    pub fn to_owned(&self) -> Cell {
        Cell {
            data: CellData::clone(&self.data),
        }
    }
}

/// An owned cell version: a cheap ref-counted handle that pins its cache block. `Send`,
/// `Sync`, `'static`; safe to hold across `.await`.
///
/// ```
/// # fn assert_owned<T: Send + Sync + 'static>() {}
/// assert_owned::<pigeonhole::Cell>();
/// ```
#[derive(Debug, Clone)]
pub struct Cell {
    data: CellData,
}

impl Cell {
    pub(crate) fn from_data(data: CellData) -> Self {
        Self { data }
    }

    /// The value bytes.
    #[inline]
    pub fn value(&self) -> &[u8] {
        payload(&self.data)
    }

    /// The typed value.
    pub fn typed(&self) -> Value<'_> {
        typed(&self.data)
    }

    /// The value as an `i64`, if it is one.
    pub fn as_i64(&self) -> Option<i64> {
        as_i64(&self.data)
    }

    /// The value as a `u64`: an `i64` value's bits, as a bitwise aggregate family holds them
    /// ([`Aggregation::BitOr`](crate::Aggregation::BitOr), D298); `None` if it isn't one.
    pub fn as_u64(&self) -> Option<u64> {
        as_i64(&self.data).map(|v| v as u64)
    }

    /// The value as an `f64`, if it is one (an `f64` aggregate family's cells are).
    pub fn as_f64(&self) -> Option<f64> {
        as_f64(&self.data)
    }

    /// The value as a vector, if it is one (a vector family's cells are, D303).
    pub fn as_vector(&self) -> Option<crate::VectorRef<'_>> {
        match self.data.value() {
            ValueRef::Vector(v) => Some(crate::VectorRef::new(v)),
            _ => None,
        }
    }

    /// The sum an exact-sum state holds, rounded once to the nearest `f64`, as an exact-sum
    /// family's cells hold ([`Aggregation::SumF64`](crate::Aggregation::SumF64), D298). The
    /// value's shape decides, as for [`hll_estimate`](Self::hll_estimate): `None` unless it
    /// is a well-formed state.
    pub fn sum_f64(&self) -> Option<f64> {
        sum_f64(&self.data)
    }

    /// The count, mean and variance a mean-variance state holds
    /// ([`Aggregation::MeanVar`](crate::Aggregation::MeanVar), D298); `None` unless the value
    /// is a well-formed one.
    pub fn mean_var(&self) -> Option<MeanVar> {
        mean_var(&self.data)
    }

    /// The per-bucket counts a histogram state holds, one per bucket of the family's
    /// [`HistogramParams`](crate::HistogramParams) (D298); `None` unless the value is a
    /// well-formed one.
    pub fn histogram_counts(&self) -> Option<Vec<u64>> {
        histogram_counts(&self.data)
    }

    /// The `q`-quantile (`0 ≤ q ≤ 1`) a quantile sketch holds
    /// ([`Aggregation::Quantiles`](crate::Aggregation::Quantiles), D298): its bucket's
    /// midpoint for the input of rank `⌊q·(n−1)⌋`, within a relative error of 2^-p while
    /// nothing has collapsed. `None` unless the value is a well-formed sketch and `q` is in
    /// range.
    pub fn quantile(&self, q: f64) -> Option<f64> {
        quantile(&self.data, q)
    }

    /// The number of inputs a quantile sketch holds.
    pub fn quantiles_count(&self) -> Option<u64> {
        quantiles_count(&self.data)
    }

    /// Whether a bloom filter ([`Aggregation::Bloom`](crate::Aggregation::Bloom), D298) may
    /// hold the `i64` element `v`: `Some(false)` means certainly not. `None` unless the value
    /// is a well-formed filter.
    pub fn bloom_contains(&self, v: i64) -> Option<bool> {
        bloom_contains(&self.data, pigeonhole_format::hll::hash_i64(v))
    }

    /// [`bloom_contains`](Self::bloom_contains) for a bytes element, as
    /// [`aggregate_bytes`](crate::RowMutation::aggregate_bytes) writes one.
    pub fn bloom_contains_bytes(&self, v: &[u8]) -> Option<bool> {
        bloom_contains(&self.data, pigeonhole_format::hll::hash_bytes(v))
    }

    /// The fraction of a bloom filter's bits set: its false-positive rate is about this to
    /// the power of its hashes.
    pub fn bloom_fill(&self) -> Option<f64> {
        bloom_fill(&self.data)
    }

    /// The set a set family's cell holds ([`Aggregation::Set`](crate::Aggregation::Set),
    /// D298), read in place. `None` unless the value is a well-formed set.
    pub fn as_set(&self) -> Option<crate::SetRef<'_>> {
        match self.data.value() {
            ValueRef::Bytes(b) => crate::SetRef::from_bytes(b),
            _ => None,
        }
    }

    /// The estimated number of distinct elements of an HLL sketch value, as an HLL family's
    /// cells hold ([`Aggregation::Hll`](crate::Aggregation::Hll), D294), about 1.6% standard
    /// error. The value's shape decides, not its family: `None` unless it is a well-formed
    /// sketch.
    pub fn hll_estimate(&self) -> Option<u64> {
        hll_estimate(&self.data)
    }

    /// The version's timestamp.
    pub fn timestamp(&self) -> u64 {
        self.data.timestamp()
    }
}

/// One entry of a row: which column, and which version.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct CellEntry<'a> {
    /// Family name.
    pub family: &'a str,
    /// Qualifier.
    pub qualifier: &'a [u8],
    /// The version.
    pub cell: CellRef<'a>,
}

/// One cell of a row: its family (an index into the row's catalog entry), its qualifier as
/// a range of the row's qualifier buffer, and the version.
#[derive(Debug, Clone)]
pub(crate) struct RowCell {
    family: usize,
    qualifier: Range<usize>,
    cell: Cell,
}

/// A table's row sizes, for sizing a point read's buffers up front (#1558 item 1): without
/// it each read grew its qualifiers and cells from empty, a `realloc` per doubling,
/// which was the top allocation site on ycsb-c (g50). Each is the largest seen, capped, so
/// it stops changing once the table's rows have been seen: after that the shared handle's
/// counters are only read, never written.
#[derive(Debug, Default)]
pub(crate) struct RowShape {
    qualifiers: AtomicU32,
    cells: AtomicU32,
}

impl RowShape {
    /// The caps: a row larger than this still reads correctly, it just grows past them.
    const QUALIFIERS_MAX: u32 = 4 << 10;
    const CELLS_MAX: u32 = 64;

    /// An empty row for `info`'s families, with room for the largest row seen (capped). Not
    /// the key: a point read moves the caller's key in. Its buffers are a row this thread
    /// dropped, if one is pooled (#1558 item 2), else new.
    #[inline]
    pub(crate) fn buf(&self, info: Arc<TableInfo>) -> RowBuf {
        let (qualifiers, cells) = self.buffers();
        RowBuf {
            info: Some(info),
            key: Vec::new(),
            qualifiers,
            cells,
            last_family: None,
        }
    }

    /// [`RowShape::buf`]'s buffers: a pooled pair if there is one, with room reserved.
    #[inline]
    fn buffers(&self) -> Pooled {
        let (mut q, mut c) = recycled().unwrap_or_default();
        q.reserve(self.qualifiers.load(Relaxed) as usize);
        c.reserve(self.cells.load(Relaxed) as usize);
        (q, c)
    }

    /// Records `buf`'s sizes if one is larger than seen so far (and under its cap), and
    /// trims a buffer far larger than its row before the row goes to the caller (perf2's
    /// R1 on #1677): a caller may keep the row, and a 1-cell row sized for the table's widest
    /// would hold some 15 KiB. A table of like-sized rows never trims.
    #[inline]
    pub(crate) fn observe(&self, buf: &mut RowBuf) {
        buf.fit();
        self.record(buf);
    }

    #[inline]
    fn record(&self, buf: &RowBuf) {
        fn grow(at: &AtomicU32, len: usize, max: u32) {
            let len = (len as u32).min(max);
            if len > at.load(Relaxed) {
                at.fetch_max(len, Relaxed);
            }
        }
        grow(&self.qualifiers, buf.qualifiers.len(), Self::QUALIFIERS_MAX);
        grow(&self.cells, buf.cells.len(), Self::CELLS_MAX);
    }
}

/// Rows' buffers a thread keeps for its next point reads (#1558 item 2): a dropped row's
/// qualifiers and cells, emptied, so a thread reading row after row stops allocating them.
/// Bounded in count and in each buffer's size ([`RowShape`]'s caps): with a cell about 170
/// bytes (an inline value's 128-byte array), a thread holds at most about 4 × (4 KiB +
/// 64 × 170 B) ≈ 60 KiB. A row dropped on another thread feeds that thread's pool: nothing
/// crosses threads, and no lock is taken.
const POOLED_ROWS: usize = 4;

type Pooled = (Vec<u8>, Vec<RowCell>);

thread_local! {
    static POOL: std::cell::RefCell<Vec<Pooled>> = const { std::cell::RefCell::new(Vec::new()) };
}

/// A pooled pair of buffers, if this thread has one.
#[inline]
fn recycled() -> Option<Pooled> {
    POOL.try_with(|p| p.try_borrow_mut().ok()?.pop())
        .ok()
        .flatten()
}

impl Drop for RowBuf {
    fn drop(&mut self) {
        let (q, c) = (&mut self.qualifiers, &mut self.cells);
        if q.capacity() == 0
            || q.capacity() > RowShape::QUALIFIERS_MAX as usize
            || c.capacity() > RowShape::CELLS_MAX as usize
        {
            return;
        }
        let (mut q, mut c) = (std::mem::take(q), std::mem::take(c));
        q.clear();
        c.clear();
        // At thread exit the pool may be gone; the buffers are then just freed.
        let _ = POOL.try_with(|p| {
            if let Ok(mut p) = p.try_borrow_mut()
                && p.len() < POOLED_ROWS
            {
                p.push((q, c));
            }
        });
    }
}

/// The storage behind [`Row`] and [`RowRef`]: a few buffers per row, none per cell.
#[derive(Debug, Clone, Default)]
pub(crate) struct RowBuf {
    /// Names the families (a catalog entry that includes every family read).
    pub(crate) info: Option<Arc<TableInfo>>,
    pub(crate) key: Vec<u8>,
    /// Every qualifier of the row, concatenated.
    pub(crate) qualifiers: Vec<u8>,
    cells: Vec<RowCell>,
    /// The family pushed last and its index in `info`: cells come grouped by family, so
    /// resolving one is a lookup per family run, not per cell.
    last_family: Option<(FamilyId, usize)>,
}

impl pigeonhole_engine::RowSink for RowBuf {
    fn qualifiers(&mut self) -> &mut Vec<u8> {
        &mut self.qualifiers
    }

    fn push(&mut self, family: FamilyId, qualifier: Range<usize>, data: CellData) {
        RowBuf::push(self, family, qualifier, data);
    }

    // Inlined into the row read's per-cell loop: with the row cache's hit path as a second
    // caller, a plain `#[inline]` stopped being honored there (#404, +0.7% on ycsb-a).
    #[inline(always)]
    fn push_inline(&mut self, family: FamilyId, qualifier: Range<usize>, ts: u64, stored: &[u8]) {
        let family = self.family_index(family);
        self.cells.push(RowCell {
            family,
            qualifier,
            cell: Cell {
                data: CellData::EMPTY,
            },
        });
        if let Some(c) = self.cells.last_mut() {
            c.cell.data.set_inline(ts, stored);
        }
    }

    fn cell_count(&self) -> Option<usize> {
        Some(self.cells.len())
    }

    fn cell(&self, i: usize) -> Option<(&[u8], &CellData)> {
        let c = self.cells.get(i)?;
        Some((self.qualifiers.get(c.qualifier.clone())?, &c.cell.data))
    }
}

impl RowBuf {
    /// An empty row whose families are named by `info`, with room for `cells` cells.
    pub(crate) fn new(info: Arc<TableInfo>, cells: usize) -> Self {
        Self {
            info: Some(info),
            key: Vec::new(),
            qualifiers: Vec::new(),
            cells: Vec::with_capacity(cells),
            last_family: None,
        }
    }

    /// An empty row for the same families, with this row's capacities (the next row of a
    /// scan is likely shaped like the last).
    pub(crate) fn empty_like(&self) -> Self {
        Self {
            info: self.info.clone(),
            key: Vec::with_capacity(self.key.len()),
            qualifiers: Vec::with_capacity(self.qualifiers.len()),
            cells: Vec::with_capacity(self.cells.len()),
            last_family: self.last_family,
        }
    }

    /// Shrinks a buffer more than four times its length (with a floor of 4 cells and 256
    /// qualifier bytes) to that floor or its length, for a row handed to a caller.
    #[inline]
    pub(crate) fn fit(&mut self) {
        let cells = self.cells.len().max(4);
        if self.cells.capacity() > 4 * cells {
            self.cells.shrink_to(cells);
        }
        let qualifiers = self.qualifiers.len().max(256);
        if self.qualifiers.capacity() > 4 * qualifiers {
            self.qualifiers.shrink_to(qualifiers);
        }
    }

    /// Empties the buffers, keeping their capacity.
    pub(crate) fn clear(&mut self) {
        self.key.clear();
        self.qualifiers.clear();
        self.cells.clear();
    }

    /// Number of cells.
    pub(crate) fn len(&self) -> usize {
        self.cells.len()
    }

    /// Whether cells `i` and `j` are versions of one column (family and qualifier).
    pub(crate) fn same_column(&self, i: usize, j: usize) -> bool {
        let (a, b) = (&self.cells[i], &self.cells[j]);
        a.family == b.family
            && self.qualifiers[a.qualifier.clone()] == self.qualifiers[b.qualifier.clone()]
    }

    /// Moves the cells from `from` on (versions of one column) out to `out`, with their family
    /// (as an index into `info`), and the column's qualifier to `qualifier`; the row keeps the
    /// cells before `from`.
    pub(crate) fn split_off_column(
        &mut self,
        from: usize,
        out: &mut Vec<(usize, CellData)>,
        qualifier: &mut Vec<u8>,
    ) {
        let range = self.cells[from].qualifier.clone();
        qualifier.clear();
        qualifier.extend_from_slice(&self.qualifiers[range.clone()]);
        out.extend(self.cells.drain(from..).map(|c| (c.family, c.cell.data)));
        self.qualifiers.truncate(range.start);
    }

    /// Appends the versions of one column taken out by [`RowBuf::split_off_column`].
    pub(crate) fn push_column(&mut self, cells: &mut Vec<(usize, CellData)>, qualifier: &[u8]) {
        let start = self.qualifiers.len();
        self.qualifiers.extend_from_slice(qualifier);
        let range = start..self.qualifiers.len();
        self.cells
            .extend(cells.drain(..).map(|(family, data)| RowCell {
                family,
                qualifier: range.clone(),
                cell: Cell { data },
            }));
    }

    /// The last cell's family and qualifier.
    pub(crate) fn last_column(&self) -> Option<(FamilyId, &[u8])> {
        let c = self.cells.last()?;
        let family = self.info.as_ref()?.families.get(c.family)?.id;
        Some((family, &self.qualifiers[c.qualifier.clone()]))
    }

    /// Appends a cell whose qualifier is `qualifier` within `qualifiers`.
    pub(crate) fn push(&mut self, family: FamilyId, qualifier: Range<usize>, data: CellData) {
        let family = self.family_index(family);
        self.cells.push(RowCell {
            family,
            qualifier,
            cell: Cell { data },
        });
    }

    /// The index of family `id` in `info` (`usize::MAX` if it is not there, which names it
    /// `""`).
    fn family_index(&mut self, id: FamilyId) -> usize {
        if let Some((last, i)) = self.last_family
            && last == id
        {
            return i;
        }
        let i = self
            .info
            .as_deref()
            .and_then(|info| info.families.iter().position(|f| f.id == id))
            .unwrap_or(usize::MAX);
        self.last_family = Some((id, i));
        i
    }

    fn family_name(&self, i: usize) -> &str {
        self.info
            .as_deref()
            .and_then(|info| info.families.get(i))
            .map_or("", |f| f.name.as_str())
    }

    fn qualifier(&self, cell: &RowCell) -> &[u8] {
        &self.qualifiers[cell.qualifier.clone()]
    }

    fn entry(&self, i: usize) -> Option<(&str, &[u8], &Cell)> {
        let c = self.cells.get(i)?;
        Some((self.family_name(c.family), self.qualifier(c), &c.cell))
    }

    /// The newest version of one column: the first cell of it, since versions come newest
    /// first.
    fn get(&self, family: &str, qualifier: &[u8]) -> Option<&Cell> {
        let i = self
            .info
            .as_deref()?
            .families
            .iter()
            .position(|f| f.name == family)?;
        self.cells
            .iter()
            .find(|c| c.family == i && self.qualifier(c) == qualifier)
            .map(|c| &c.cell)
    }
}

/// Where a [`RowRef`] gets its cells.
#[derive(Debug, Clone)]
enum RowSrc<'a> {
    Owned(Arc<RowBuf>),
    Borrowed(&'a RowBuf),
}

/// A borrowed row: its key and its cells ordered by family, qualifier, newest version first.
///
/// ```
/// use pigeonhole::{Family, Options, Pigeonhole};
///
/// # fn main() -> pigeonhole::Result<()> {
/// # let dir = pigeonhole::doc_support::temp_dir();
/// let db = Pigeonhole::open(dir.join("app.phdb"), Options::default().shards(1))?;
/// let t = db
///     .table("t")?
///     .family("a", Family::default())
///     .family("b", Family::default())
///     .create_if_missing()?;
/// t.mutate(b"row").put("b", b"x", b"1").put("a", b"z", b"2").put("a", b"y", b"3").commit()?;
///
/// let row = t.row(b"row").read()?.unwrap();
/// assert_eq!(row.key(), b"row");
/// let cells: Vec<(&str, &[u8])> = row.iter().map(|e| (e.family, e.qualifier)).collect();
/// assert_eq!(cells, [("a", &b"y"[..]), ("a", b"z"), ("b", b"x")]);
/// assert_eq!(row.get("a", b"z").unwrap().value(), b"2");
/// # db.close()?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct RowRef<'a> {
    src: RowSrc<'a>,
}

impl<'a> RowRef<'a> {
    pub(crate) fn owned(buf: RowBuf) -> Self {
        Self {
            src: RowSrc::Owned(Arc::new(buf)),
        }
    }

    pub(crate) fn borrowed(buf: &'a RowBuf) -> Self {
        Self {
            src: RowSrc::Borrowed(buf),
        }
    }

    fn buf(&self) -> &RowBuf {
        match &self.src {
            RowSrc::Owned(b) => b,
            RowSrc::Borrowed(b) => b,
        }
    }

    /// The row key.
    pub fn key(&self) -> &[u8] {
        &self.buf().key
    }

    /// Number of cells.
    pub fn len(&self) -> usize {
        self.buf().len()
    }

    /// Whether the row has no cells.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// The `i`th cell.
    pub fn entry(&self, i: usize) -> Option<CellEntry<'_>> {
        let (family, qualifier, cell) = self.buf().entry(i)?;
        Some(CellEntry {
            family,
            qualifier,
            cell: CellRef::borrowed(&cell.data),
        })
    }

    /// Iterates the cells.
    pub fn iter(&self) -> impl Iterator<Item = CellEntry<'_>> + '_ {
        (0..self.len()).filter_map(move |i| self.entry(i))
    }

    /// The newest version of one column.
    pub fn get(&self, family: &str, qualifier: &[u8]) -> Option<CellRef<'_>> {
        self.buf()
            .get(family, qualifier)
            .map(|c| CellRef::borrowed(&c.data))
    }

    /// An owned copy of the row's structure; values stay pinned, not copied.
    pub fn to_owned(&self) -> Row {
        let buf = match &self.src {
            RowSrc::Owned(b) => Arc::clone(b),
            RowSrc::Borrowed(b) => Arc::new(RowBuf::clone(b)),
        };
        Row { buf }
    }
}

/// An owned row. Cheap to clone.
///
/// ```
/// use pigeonhole::{Family, Options, Pigeonhole, Row};
///
/// # fn main() -> pigeonhole::Result<()> {
/// # let dir = pigeonhole::doc_support::temp_dir();
/// let db = Pigeonhole::open(dir.join("app.phdb"), Options::default().shards(1))?;
/// let t = db.table("t")?.family("f", Family::default()).create_if_missing()?;
/// t.mutate(b"a").put("f", b"q", b"1").commit()?;
/// t.mutate(b"b").put("f", b"q", b"2").commit()?;
///
/// let rows: Vec<Row> = t.scan_prefix(b"").iter()?.collect::<pigeonhole::Result<_>>()?;
/// assert_eq!(rows.len(), 2);
/// let e = rows[1].entry(0).unwrap();
/// assert_eq!((e.family, e.qualifier, e.cell.value()), ("f", &b"q"[..], &b"2"[..]));
/// assert_eq!(rows[0].get("f", b"q").unwrap().value(), b"1");
/// # db.close()?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct Row {
    buf: Arc<RowBuf>,
}

impl Row {
    pub(crate) fn new(buf: RowBuf) -> Self {
        Self { buf: Arc::new(buf) }
    }

    /// The row key.
    pub fn key(&self) -> &[u8] {
        &self.buf.key
    }

    /// Number of cells.
    pub fn len(&self) -> usize {
        self.buf.len()
    }

    /// Whether the row has no cells.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// The `i`th cell, as [`RowRef::entry`] gives it (ICR 0086).
    pub fn entry(&self, i: usize) -> Option<CellEntry<'_>> {
        let (family, qualifier, cell) = self.buf.entry(i)?;
        Some(CellEntry {
            family,
            qualifier,
            cell: CellRef::borrowed(&cell.data),
        })
    }

    /// The newest version of one column.
    pub fn get(&self, family: &str, qualifier: &[u8]) -> Option<&Cell> {
        self.buf.get(family, qualifier)
    }

    /// A borrowed view.
    pub fn view(&self) -> RowRef<'_> {
        RowRef::borrowed(&self.buf)
    }
}

#[cfg(test)]
mod pool_tests {
    use super::*;

    /// The calling thread's pooled pairs (an inspection helper).
    fn pooled() -> usize {
        POOL.with(|p| p.borrow().len())
    }

    fn drain() {
        POOL.with(|p| p.borrow_mut().clear());
    }

    /// A row with `cells` empty cells and `q` qualifier bytes, with exactly that capacity.
    fn row(cells: usize, q: usize) -> RowBuf {
        let mut b = RowBuf::default();
        b.qualifiers.reserve_exact(q);
        b.qualifiers.resize(q, b'q');
        b.cells.reserve_exact(cells);
        for _ in 0..cells {
            b.cells.push(RowCell {
                family: 0,
                qualifier: 0..1,
                cell: Cell {
                    data: CellData::EMPTY,
                },
            });
        }
        b
    }

    /// A row from `shape`'s buffers, as a point read starts one.
    fn started(shape: &RowShape) -> RowBuf {
        let (qualifiers, cells) = shape.buffers();
        let mut b = RowBuf::default();
        b.qualifiers = qualifiers;
        b.cells = cells;
        b
    }

    /// perf2's R1: a small row read after the table's widest doesn't keep the widest's
    /// capacity once it's handed out.
    #[test]
    fn a_small_row_after_a_wide_one_keeps_a_small_capacity() {
        drain();
        let shape = RowShape::default();
        let mut wide = row(64, 4096);
        shape.observe(&mut wide);
        drop(wide);
        // The same table: sized from the shape (and from the pooled wide pair).
        let mut small = started(&shape);
        small.qualifiers.extend_from_slice(b"q");
        small.cells.append(&mut row(1, 0).cells);
        shape.observe(&mut small);
        assert!(
            small.cells.capacity() <= 16,
            "{} cells",
            small.cells.capacity()
        );
        assert!(
            small.qualifiers.capacity() <= 1024,
            "{} bytes",
            small.qualifiers.capacity()
        );
        // Another table (a fresh shape), through the pool only.
        drop(row(64, 4096));
        let other = RowShape::default();
        let mut small = started(&other);
        assert!(small.cells.capacity() >= 64, "the pooled pair was taken");
        small.cells.append(&mut row(1, 0).cells);
        other.observe(&mut small);
        assert!(
            small.cells.capacity() <= 16,
            "{} cells",
            small.cells.capacity()
        );
    }

    #[test]
    fn the_pool_keeps_four_pairs_within_the_caps() {
        drain();
        for _ in 0..6 {
            drop(row(8, 64));
        }
        assert_eq!(pooled(), 4);
        drain();
        drop(row(RowShape::CELLS_MAX as usize + 1, 64));
        drop(row(8, RowShape::QUALIFIERS_MAX as usize + 1));
        assert_eq!(pooled(), 0, "an over-cap row isn't pooled");
    }

    /// A row dropped by another thread-local's destructor, after the pool may be gone, is
    /// freed without a panic (`try_with`; destructor order isn't specified).
    #[test]
    fn a_row_dropped_at_thread_exit_does_not_panic() {
        thread_local! {
            static HELD: std::cell::RefCell<Option<RowBuf>> = const { std::cell::RefCell::new(None) };
        }
        std::thread::spawn(|| {
            drop(row(8, 64)); // the pool exists
            HELD.with(|h| *h.borrow_mut() = Some(row(8, 64)));
        })
        .join()
        .expect("thread exit with a held row");
    }
}