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};
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub enum Value<'a> {
Bytes(&'a [u8]),
I64(i64),
F64(f64),
Varint(i64),
Vector(crate::VectorRef<'a>),
}
#[inline]
fn payload(data: &CellData) -> &[u8] {
data.stored().get(1..).unwrap_or_default()
}
fn typed(data: &CellData) -> Value<'_> {
typed_value(data.value())
}
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)),
ValueRef::Blob(_) => Value::Bytes(&[]),
}
}
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,
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MeanVar {
count: u64,
mean: f64,
variance: f64,
sample_variance: Option<f64>,
}
impl MeanVar {
pub fn count(&self) -> u64 {
self.count
}
pub fn mean(&self) -> f64 {
self.mean
}
pub fn variance(&self) -> f64 {
self.variance
}
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,
}
}
#[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),
}
}
#[inline]
pub fn value(&self) -> &[u8] {
payload(&self.data)
}
pub fn typed(&self) -> Value<'_> {
typed(&self.data)
}
pub fn as_i64(&self) -> Option<i64> {
as_i64(&self.data)
}
pub fn as_u64(&self) -> Option<u64> {
as_i64(&self.data).map(|v| v as u64)
}
pub fn as_f64(&self) -> Option<f64> {
as_f64(&self.data)
}
pub fn as_vector(&self) -> Option<crate::VectorRef<'_>> {
match self.data.value() {
ValueRef::Vector(v) => Some(crate::VectorRef::new(v)),
_ => None,
}
}
pub fn sum_f64(&self) -> Option<f64> {
sum_f64(&self.data)
}
pub fn mean_var(&self) -> Option<MeanVar> {
mean_var(&self.data)
}
pub fn histogram_counts(&self) -> Option<Vec<u64>> {
histogram_counts(&self.data)
}
pub fn quantile(&self, q: f64) -> Option<f64> {
quantile(&self.data, q)
}
pub fn quantiles_count(&self) -> Option<u64> {
quantiles_count(&self.data)
}
pub fn bloom_contains(&self, v: i64) -> Option<bool> {
bloom_contains(&self.data, pigeonhole_format::hll::hash_i64(v))
}
pub fn bloom_contains_bytes(&self, v: &[u8]) -> Option<bool> {
bloom_contains(&self.data, pigeonhole_format::hll::hash_bytes(v))
}
pub fn bloom_fill(&self) -> Option<f64> {
bloom_fill(&self.data)
}
pub fn as_set(&self) -> Option<crate::SetRef<'_>> {
match self.data.value() {
ValueRef::Bytes(b) => crate::SetRef::from_bytes(b),
_ => None,
}
}
pub fn hll_estimate(&self) -> Option<u64> {
hll_estimate(&self.data)
}
pub fn timestamp(&self) -> u64 {
self.data.timestamp()
}
pub fn to_owned(&self) -> Cell {
Cell {
data: CellData::clone(&self.data),
}
}
}
#[derive(Debug, Clone)]
pub struct Cell {
data: CellData,
}
impl Cell {
pub(crate) fn from_data(data: CellData) -> Self {
Self { data }
}
#[inline]
pub fn value(&self) -> &[u8] {
payload(&self.data)
}
pub fn typed(&self) -> Value<'_> {
typed(&self.data)
}
pub fn as_i64(&self) -> Option<i64> {
as_i64(&self.data)
}
pub fn as_u64(&self) -> Option<u64> {
as_i64(&self.data).map(|v| v as u64)
}
pub fn as_f64(&self) -> Option<f64> {
as_f64(&self.data)
}
pub fn as_vector(&self) -> Option<crate::VectorRef<'_>> {
match self.data.value() {
ValueRef::Vector(v) => Some(crate::VectorRef::new(v)),
_ => None,
}
}
pub fn sum_f64(&self) -> Option<f64> {
sum_f64(&self.data)
}
pub fn mean_var(&self) -> Option<MeanVar> {
mean_var(&self.data)
}
pub fn histogram_counts(&self) -> Option<Vec<u64>> {
histogram_counts(&self.data)
}
pub fn quantile(&self, q: f64) -> Option<f64> {
quantile(&self.data, q)
}
pub fn quantiles_count(&self) -> Option<u64> {
quantiles_count(&self.data)
}
pub fn bloom_contains(&self, v: i64) -> Option<bool> {
bloom_contains(&self.data, pigeonhole_format::hll::hash_i64(v))
}
pub fn bloom_contains_bytes(&self, v: &[u8]) -> Option<bool> {
bloom_contains(&self.data, pigeonhole_format::hll::hash_bytes(v))
}
pub fn bloom_fill(&self) -> Option<f64> {
bloom_fill(&self.data)
}
pub fn as_set(&self) -> Option<crate::SetRef<'_>> {
match self.data.value() {
ValueRef::Bytes(b) => crate::SetRef::from_bytes(b),
_ => None,
}
}
pub fn hll_estimate(&self) -> Option<u64> {
hll_estimate(&self.data)
}
pub fn timestamp(&self) -> u64 {
self.data.timestamp()
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct CellEntry<'a> {
pub family: &'a str,
pub qualifier: &'a [u8],
pub cell: CellRef<'a>,
}
#[derive(Debug, Clone)]
pub(crate) struct RowCell {
family: usize,
qualifier: Range<usize>,
cell: Cell,
}
#[derive(Debug, Default)]
pub(crate) struct RowShape {
qualifiers: AtomicU32,
cells: AtomicU32,
}
impl RowShape {
const QUALIFIERS_MAX: u32 = 4 << 10;
const CELLS_MAX: u32 = 64;
#[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,
}
}
#[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)
}
#[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);
}
}
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()) };
}
#[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();
let _ = POOL.try_with(|p| {
if let Ok(mut p) = p.try_borrow_mut()
&& p.len() < POOLED_ROWS
{
p.push((q, c));
}
});
}
}
#[derive(Debug, Clone, Default)]
pub(crate) struct RowBuf {
pub(crate) info: Option<Arc<TableInfo>>,
pub(crate) key: Vec<u8>,
pub(crate) qualifiers: Vec<u8>,
cells: Vec<RowCell>,
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);
}
#[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 {
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,
}
}
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,
}
}
#[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);
}
}
pub(crate) fn clear(&mut self) {
self.key.clear();
self.qualifiers.clear();
self.cells.clear();
}
pub(crate) fn len(&self) -> usize {
self.cells.len()
}
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()]
}
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);
}
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 },
}));
}
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()]))
}
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 },
});
}
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))
}
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)
}
}
#[derive(Debug, Clone)]
enum RowSrc<'a> {
Owned(Arc<RowBuf>),
Borrowed(&'a RowBuf),
}
#[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,
}
}
pub fn key(&self) -> &[u8] {
&self.buf().key
}
pub fn len(&self) -> usize {
self.buf().len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
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),
})
}
pub fn iter(&self) -> impl Iterator<Item = CellEntry<'_>> + '_ {
(0..self.len()).filter_map(move |i| self.entry(i))
}
pub fn get(&self, family: &str, qualifier: &[u8]) -> Option<CellRef<'_>> {
self.buf()
.get(family, qualifier)
.map(|c| CellRef::borrowed(&c.data))
}
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 }
}
}
#[derive(Debug, Clone)]
pub struct Row {
buf: Arc<RowBuf>,
}
impl Row {
pub(crate) fn new(buf: RowBuf) -> Self {
Self { buf: Arc::new(buf) }
}
pub fn key(&self) -> &[u8] {
&self.buf.key
}
pub fn len(&self) -> usize {
self.buf.len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
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),
})
}
pub fn get(&self, family: &str, qualifier: &[u8]) -> Option<&Cell> {
self.buf.get(family, qualifier)
}
pub fn view(&self) -> RowRef<'_> {
RowRef::borrowed(&self.buf)
}
}
#[cfg(test)]
mod pool_tests {
use super::*;
fn pooled() -> usize {
POOL.with(|p| p.borrow().len())
}
fn drain() {
POOL.with(|p| p.borrow_mut().clear());
}
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
}
fn started(shape: &RowShape) -> RowBuf {
let (qualifiers, cells) = shape.buffers();
let mut b = RowBuf::default();
b.qualifiers = qualifiers;
b.cells = cells;
b
}
#[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);
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()
);
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");
}
#[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)); HELD.with(|h| *h.borrow_mut() = Some(row(8, 64)));
})
.join()
.expect("thread exit with a held row");
}
}