use std::cell::RefCell;
use std::sync::{Arc, Weak};
use relate_core::Value;
use super::fold::membership;
const MIN_INDEXED_LEN: usize = 9;
const MAX_INDEXED_LEN: usize = 65_536;
const MAX_INDEXED_STRING_BYTES: usize = 1 << 20;
enum Index {
Ints(Vec<i64>),
Strings(Vec<Arc<str>>),
Unindexable,
}
struct Slot {
list: Weak<Vec<Value>>,
index: Option<Index>,
}
thread_local! {
static LAST: RefCell<Option<Slot>> = const { RefCell::new(None) };
}
fn table<T: Ord>(items: impl Iterator<Item = Option<T>>) -> Option<Vec<T>> {
let mut table: Vec<T> = items.collect::<Option<_>>()?;
table.sort_unstable();
table.dedup();
Some(table)
}
fn build(list: &[Value]) -> Index {
if list.len() > MAX_INDEXED_LEN {
return Index::Unindexable;
}
match list.first() {
Some(Value::Int(_)) => table(list.iter().map(|v| match v {
Value::Int(i) => Some(*i),
_ => None,
}))
.map(Index::Ints)
.unwrap_or(Index::Unindexable),
Some(Value::String(_)) => {
let Some(strings) = table(list.iter().map(|v| match v {
Value::String(s) => Some(Arc::clone(s)),
_ => None,
})) else {
return Index::Unindexable;
};
let string_bytes: usize = strings.iter().map(|s| s.len()).sum();
if string_bytes > MAX_INDEXED_STRING_BYTES {
return Index::Unindexable;
}
Index::Strings(strings)
}
_ => Index::Unindexable,
}
}
pub(crate) fn member_of(x: &Value, list: &Arc<Vec<Value>>) -> Value {
indexed_membership(x, list).map_or_else(|| membership(x, list), Value::Bool)
}
fn indexed_membership(x: &Value, list: &Arc<Vec<Value>>) -> Option<bool> {
if list.len() < MIN_INDEXED_LEN || !matches!(x, Value::Int(_) | Value::String(_)) {
return None;
}
LAST.with(|cell| {
let mut slot = cell.borrow_mut();
let seen = match slot.as_mut() {
Some(s) if s.list.as_ptr() == Arc::as_ptr(list) => s,
_ => {
*slot = Some(Slot {
list: Arc::downgrade(list),
index: None,
});
return None;
}
};
match (x, seen.index.get_or_insert_with(|| build(list))) {
(Value::Int(i), Index::Ints(ints)) => Some(ints.binary_search(i).is_ok()),
(Value::String(s), Index::Strings(strings)) => {
Some(strings.binary_search_by(|m| (**m).cmp(&**s)).is_ok())
}
_ => None,
}
})
}
#[cfg(test)]
mod tests {
use super::super::fold::membership;
use super::*;
fn ints(xs: &[i64]) -> Arc<Vec<Value>> {
Arc::new(xs.iter().map(|i| Value::Int(*i)).collect())
}
fn agrees(probe: &Value, list: &Arc<Vec<Value>>) {
let scan = membership(probe, list);
for _ in 0..3 {
assert_eq!(
member_of(probe, list),
scan,
"probe {probe:?} over {list:?}"
);
}
}
fn probes() -> Vec<Value> {
vec![
Value::Null,
Value::Int(0),
Value::Int(5),
Value::Int(-3),
Value::Int(i64::MAX),
Value::Float(5.0),
Value::Float(5.5),
Value::Float(f64::NAN),
Value::Bool(true),
Value::String("a".into()),
Value::String("".into()),
Value::String("zz".into()),
Value::List(Arc::new(vec![Value::Int(1)])),
]
}
#[test]
fn matches_the_scan_over_adversarial_lists() {
let strings = |xs: &[&str]| {
Arc::new(
xs.iter()
.map(|s| Value::String((*s).into()))
.collect::<Vec<_>>(),
)
};
let mut lists = vec![
ints(&[]),
ints(&[1, 2, 3]),
ints(&[9, 5, 5, 1, 0, -3, 7, 7, 2, 4, 6, i64::MAX]),
strings(&["a", "b", "a", "c", "d", "e", "f", "g", "h", "i", ""]),
];
let mut with_null = (0..12).map(Value::Int).collect::<Vec<_>>();
with_null.push(Value::Null);
lists.push(Arc::new(with_null));
let mut with_float = (0..12).map(Value::Int).collect::<Vec<_>>();
with_float.push(Value::Float(5.0));
lists.push(Arc::new(with_float));
let mut with_nan = (0..12).map(Value::Int).collect::<Vec<_>>();
with_nan.push(Value::Float(f64::NAN));
lists.push(Arc::new(with_nan));
let mut mixed = (0..6).map(Value::Int).collect::<Vec<_>>();
mixed.extend((0..6).map(|i| Value::String(format!("s{i}").into())));
lists.push(Arc::new(mixed));
for list in &lists {
for probe in probes() {
agrees(&probe, list);
}
}
}
#[test]
fn builds_only_on_the_second_sighting_of_one_allocation() {
let list = ints(&(0..20).collect::<Vec<_>>());
assert_eq!(indexed_membership(&Value::Int(3), &list), None);
assert_eq!(indexed_membership(&Value::Int(3), &list), Some(true));
assert_eq!(indexed_membership(&Value::Int(99), &list), Some(false));
let other = ints(&(0..20).collect::<Vec<_>>());
assert_eq!(indexed_membership(&Value::Int(3), &other), None);
assert_eq!(indexed_membership(&Value::Int(3), &other), Some(true));
assert_eq!(indexed_membership(&Value::Null, &other), None);
assert_eq!(indexed_membership(&Value::Int(99), &other), Some(false));
}
#[test]
fn short_lists_are_never_indexed() {
let list = ints(&[1, 2, 3]);
for _ in 0..3 {
assert_eq!(indexed_membership(&Value::Int(1), &list), None);
}
}
#[test]
fn a_list_past_the_length_cap_is_never_indexed() {
let list = ints(&(0..=(MAX_INDEXED_LEN as i64)).collect::<Vec<_>>());
for _ in 0..3 {
assert_eq!(indexed_membership(&Value::Int(1), &list), None);
}
agrees(&Value::Int(1), &list);
}
#[test]
fn a_string_table_past_the_byte_cap_is_never_indexed() {
let member = "x".repeat(MAX_INDEXED_STRING_BYTES / 8 + 1);
let list: Arc<Vec<Value>> = Arc::new(
(0..16)
.map(|i| Value::String(format!("{i}{member}").into()))
.collect(),
);
let probe = Value::String(format!("0{member}").into());
for _ in 0..3 {
assert_eq!(indexed_membership(&probe, &list), None);
}
agrees(&probe, &list);
}
}