use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock, Weak};
use relate_core::Value;
use relate_names::SmallName;
const APPENDED_LINKS: usize = 8;
struct RowSchema {
names: Vec<String>,
index: HashMap<String, usize>,
appended: Mutex<Vec<(String, Weak<RowSchema>)>>,
}
const LINEAR_SLOTS: usize = 8;
impl Clone for RowSchema {
fn clone(&self) -> Self {
Self {
names: self.names.clone(),
index: self.index.clone(),
appended: Mutex::new(Vec::new()),
}
}
}
impl std::fmt::Debug for RowSchema {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RowSchema")
.field("names", &self.names)
.finish()
}
}
impl PartialEq for RowSchema {
fn eq(&self, other: &Self) -> bool {
self.names == other.names
}
}
impl Eq for RowSchema {}
impl RowSchema {
fn slot(&self, key: &str) -> Option<usize> {
if self.names.len() <= LINEAR_SLOTS {
self.names.iter().position(|n| n == key)
} else {
self.index.get(key).copied()
}
}
fn swap_remove(&mut self, slot: usize) {
let name = self.names.swap_remove(slot);
self.index.remove(&name);
if slot != self.names.len() {
let swapped = self.names[slot].clone();
self.index.insert(swapped, slot);
}
}
fn empty() -> Arc<Self> {
static EMPTY: OnceLock<Arc<RowSchema>> = OnceLock::new();
Arc::clone(EMPTY.get_or_init(|| {
Arc::new(RowSchema {
names: Vec::new(),
index: HashMap::new(),
appended: Mutex::new(Vec::new()),
})
}))
}
fn from_names(names: &[String]) -> Arc<Self> {
let mut index = HashMap::with_capacity(names.len());
for (slot, name) in names.iter().enumerate() {
index.insert(name.clone(), slot);
}
Arc::new(Self {
names: names.to_vec(),
index,
appended: Mutex::new(Vec::new()),
})
}
fn links_enabled(&self) -> bool {
!self.names.is_empty()
}
fn appended_with(&self, key: &str) -> Option<Arc<RowSchema>> {
if !self.links_enabled() {
return None;
}
let links = self.appended.lock().expect("row schema links poisoned");
links
.iter()
.find(|(name, _)| name == key)
.and_then(|(_, child)| child.upgrade())
}
fn record_appended(&self, key: &str, child: &Arc<RowSchema>) {
if !self.links_enabled() {
return;
}
let mut links = self.appended.lock().expect("row schema links poisoned");
links.retain(|(_, weak)| weak.strong_count() > 0);
if links.iter().any(|(name, _)| name == key) {
return;
}
if links.len() >= APPENDED_LINKS {
links.remove(0);
}
links.push((key.to_string(), Arc::downgrade(child)));
}
}
#[derive(Clone)]
pub(crate) struct SchemaKey(Arc<RowSchema>);
impl SchemaKey {
pub(crate) fn is(&self, row: &Row) -> bool {
std::ptr::eq(Arc::as_ptr(&self.0) as *const (), row.schema_ptr())
}
}
#[derive(Clone)]
pub struct RowNames(Arc<RowSchema>);
impl RowNames {
pub fn new(names: &[String]) -> Self {
Self(RowSchema::from_names(names))
}
pub(crate) fn names(&self) -> &[String] {
&self.0.names
}
}
#[derive(Clone)]
pub(crate) struct RowRung(Arc<RowSchema>);
impl RowRung {
pub(crate) fn from_names(names: &[String]) -> Self {
Self(interned_schema(names))
}
pub(crate) fn past<'a>(
row: &Row,
bind_names: impl IntoIterator<Item = Option<&'a str>>,
) -> Self {
let mut names: Vec<String> = row.keys().cloned().collect();
for name in bind_names {
push_bind_name(&mut names, name);
}
Self::from_names(&names)
}
pub(crate) fn names(&self) -> &[String] {
&self.0.names
}
}
pub(crate) fn push_bind_name(names: &mut Vec<String>, name: Option<&str>) {
if let Some(name) = name {
if !names.iter().any(|bound| bound.as_str() == name) {
names.push(name.to_string());
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Row {
schema: Arc<RowSchema>,
values: Vec<Value>,
}
impl Default for Row {
fn default() -> Self {
Self::new()
}
}
impl Row {
pub fn new() -> Self {
Self {
schema: RowSchema::empty(),
values: Vec::new(),
}
}
pub fn from_names(names: &RowNames, values: Vec<Value>) -> Self {
debug_assert_eq!(names.0.names.len(), values.len());
Self {
schema: Arc::clone(&names.0),
values,
}
}
pub(crate) fn stamp(&mut self, rung: &RowRung, values: impl IntoIterator<Item = Value>) {
debug_assert!(
self.values.len() <= rung.0.names.len()
&& rung.0.names[..self.values.len()] == self.schema.names[..],
"the rung's schema must extend this row's schema"
);
self.schema = Arc::clone(&rung.0);
self.values.extend(values);
debug_assert_eq!(self.values.len(), self.schema.names.len());
}
pub(crate) fn stamp_nulls(&mut self, rung: &RowRung) {
let appended = rung.0.names.len() - self.values.len();
if appended == 0 {
return;
}
self.stamp(rung, std::iter::repeat_n(Value::Null, appended));
}
pub fn swap_remove(&mut self, key: &str) -> Option<Value> {
let slot = self.schema.slot(key)?;
let removed = self.values.swap_remove(slot);
self.schema_mut().swap_remove(slot);
Some(removed)
}
pub fn len(&self) -> usize {
self.values.len()
}
pub fn is_empty(&self) -> bool {
self.values.is_empty()
}
pub fn values(&self) -> &[Value] {
&self.values
}
#[cfg(test)]
pub(crate) fn values_capacity(&self) -> usize {
self.values.capacity()
}
pub(crate) fn schema_key(&self) -> SchemaKey {
SchemaKey(Arc::clone(&self.schema))
}
pub(crate) fn schema_ptr(&self) -> *const () {
Arc::as_ptr(&self.schema) as *const ()
}
pub(crate) fn schema_bytes(&self) -> u64 {
use crate::memory::{reserved_len, OVERHEAD_MAP_ENTRY, VEC_HEADER};
let names = self.schema.names.len();
let mut bytes = if names == 0 {
0
} else {
VEC_HEADER + reserved_len(names) as u64 * std::mem::size_of::<String>() as u64
};
bytes += self.schema.index.len() as u64 * OVERHEAD_MAP_ENTRY;
for name in &self.schema.names {
bytes = bytes.saturating_add(relate_core::str_logical_bytes(name).saturating_mul(2));
}
bytes
}
pub fn get(&self, key: &str) -> Option<&Value> {
self.schema.slot(key).map(|slot| &self.values[slot])
}
pub fn get_name(&self, name: &SmallName) -> Option<&Value> {
name.with_str(|text| self.get(text))
}
pub fn get_mut(&mut self, key: &str) -> Option<&mut Value> {
let slot = self.schema.slot(key)?;
Some(&mut self.values[slot])
}
pub fn contains_key(&self, key: &str) -> bool {
self.schema.slot(key).is_some()
}
pub fn keys(&self) -> impl Iterator<Item = &String> {
self.schema.names.iter()
}
pub(crate) fn share_schemas(rows: &mut [Row]) {
let Some(first) = rows.first() else {
return;
};
let names = first.schema.names.clone();
if rows.iter().skip(1).any(|row| row.schema.names != names) {
return;
}
let shared = Arc::clone(&first.schema);
for row in rows.iter_mut().skip(1) {
row.schema = Arc::clone(&shared);
}
}
pub fn insert(&mut self, key: String, value: Value) -> Option<Value> {
if let Some(slot) = self.schema.slot(&key) {
return Some(std::mem::replace(&mut self.values[slot], value));
}
if let Some(child) = self.schema.appended_with(&key) {
self.schema = child;
self.values.push(value);
return None;
}
let mut names = self.schema.names.clone();
names.push(key);
let child = interned_schema(&names);
let key = names.last().expect("the appended name was just pushed");
self.schema.record_appended(key, &child);
self.schema = child;
self.values.push(value);
None
}
pub fn shift_remove(&mut self, key: &str) -> Option<Value> {
let slot = self.schema.slot(key)?;
let removed = std::mem::replace(&mut self.values[slot], Value::Null);
let keep: Vec<usize> = (0..self.values.len()).filter(|i| *i != slot).collect();
self.rebuild(keep);
Some(removed)
}
pub fn take_value(&mut self, key: &str) -> Option<Value> {
let slot = self.schema.slot(key)?;
Some(std::mem::replace(&mut self.values[slot], Value::Null))
}
pub fn retain(&mut self, mut keep: impl FnMut(&String, &mut Value) -> bool) {
let mut kept = Vec::with_capacity(self.values.len());
for (slot, value) in self.values.iter_mut().enumerate() {
if keep(&self.schema.names[slot], value) {
kept.push(slot);
}
}
if kept.len() != self.values.len() {
self.rebuild(kept);
}
}
pub fn entry(&mut self, key: String) -> RowEntry<'_> {
let slot = self.schema.slot(&key);
RowEntry {
row: self,
key,
slot,
}
}
pub fn iter(&self) -> impl Iterator<Item = (&String, &Value)> {
self.schema.names.iter().zip(self.values.iter())
}
pub fn iter_mut(&mut self) -> impl Iterator<Item = (&String, &mut Value)> {
self.schema.names.iter().zip(self.values.iter_mut())
}
fn schema_mut(&mut self) -> &mut RowSchema {
if Arc::get_mut(&mut self.schema).is_none() {
self.schema = Arc::new((*self.schema).clone());
}
let schema = Arc::get_mut(&mut self.schema).expect("schema was just made unique");
schema
.appended
.get_mut()
.expect("row schema links poisoned")
.clear();
schema
}
fn rebuild(&mut self, keep: Vec<usize>) {
let mut names = Vec::with_capacity(keep.len());
let mut values = Vec::with_capacity(keep.len());
for slot in keep {
names.push(self.schema.names[slot].clone());
values.push(std::mem::replace(&mut self.values[slot], Value::Null));
}
self.schema = RowSchema::from_names(&names);
self.values = values;
}
}
pub(crate) fn row_bound(row: &Row) -> impl Fn(&str) -> bool + '_ {
|name: &str| row.contains_key(name)
}
#[cfg(test)]
thread_local! {
static INTERNED_SCHEMA_CALLS: std::cell::Cell<usize> =
const { std::cell::Cell::new(0) };
}
#[cfg(test)]
pub(crate) fn interned_schema_calls() -> usize {
INTERNED_SCHEMA_CALLS.with(std::cell::Cell::get)
}
fn interned_schema(names: &[String]) -> Arc<RowSchema> {
#[cfg(test)]
INTERNED_SCHEMA_CALLS.with(|calls| calls.set(calls.get() + 1));
thread_local! {
static CACHE: RefCell<HashMap<Vec<String>, Arc<RowSchema>>> =
RefCell::new(HashMap::new());
}
CACHE.with(|cell| {
let mut cache = cell.borrow_mut();
if let Some(hit) = cache.get(names) {
return Arc::clone(hit);
}
let schema = RowSchema::from_names(names);
if cache.len() >= 128 {
cache.clear();
}
cache.insert(names.to_vec(), Arc::clone(&schema));
schema
})
}
pub struct RowEntry<'a> {
row: &'a mut Row,
key: String,
slot: Option<usize>,
}
impl<'a> RowEntry<'a> {
pub fn or_insert(self, value: Value) -> &'a mut Value {
self.or_insert_with(|| value)
}
pub fn or_insert_with<F>(self, make: F) -> &'a mut Value
where
F: FnOnce() -> Value,
{
if let Some(slot) = self.slot {
return &mut self.row.values[slot];
}
self.row.insert(self.key, make());
let slot = self.row.values.len() - 1;
&mut self.row.values[slot]
}
}
impl FromIterator<(String, Value)> for Row {
fn from_iter<I: IntoIterator<Item = (String, Value)>>(iter: I) -> Self {
let mut row = Row::new();
for (key, value) in iter {
row.insert(key, value);
}
row
}
}
impl<const N: usize> From<[(String, Value); N]> for Row {
fn from(entries: [(String, Value); N]) -> Self {
entries.into_iter().collect()
}
}
impl std::ops::Index<&str> for Row {
type Output = Value;
fn index(&self, key: &str) -> &Value {
self.get(key)
.unwrap_or_else(|| panic!("no entry found for key {key:?}"))
}
}
impl<'a> IntoIterator for &'a Row {
type Item = (&'a String, &'a Value);
type IntoIter = std::iter::Zip<std::slice::Iter<'a, String>, std::slice::Iter<'a, Value>>;
fn into_iter(self) -> Self::IntoIter {
self.schema.names.iter().zip(self.values.iter())
}
}
impl IntoIterator for Row {
type Item = (String, Value);
type IntoIter = std::vec::IntoIter<(String, Value)>;
fn into_iter(self) -> Self::IntoIter {
self.schema
.names
.iter()
.cloned()
.zip(self.values)
.collect::<Vec<_>>()
.into_iter()
}
}
#[cfg(test)]
mod tests {
use super::*;
use proptest::prelude::*;
#[test]
fn rows_inserted_with_the_same_columns_share_a_schema() {
let mut rows = Vec::new();
for i in 0..32 {
let mut row = Row::new();
row.insert("s".into(), Value::Int(i));
rows.push(row);
}
let ptr = rows[0].schema_ptr();
assert!(rows.iter().all(|row| row.schema_ptr() == ptr));
assert_eq!(rows[7].get("s"), Some(&Value::Int(7)));
}
proptest! {
#![proptest_config(crate::test_support::config_with_floor(100))]
#[test]
fn stamped_rows_match_insert_built_rows(
seed in proptest::collection::vec(("[a-z]{1,5}", any::<i64>()), 0..8),
binds in proptest::collection::vec(("[a-z]{1,5}", any::<i64>()), 0..12),
) {
let seed: Vec<(String, Value)> = seed
.into_iter()
.enumerate()
.map(|(i, (name, v))| (format!("s{name}{i}"), Value::Int(v)))
.collect();
let binds: Vec<(String, Value)> = binds
.into_iter()
.enumerate()
.map(|(i, (name, v))| (format!("b{name}{i}"), Value::Int(v)))
.collect();
let mut inserted = Row::new();
for (name, value) in seed.iter().chain(binds.iter()) {
inserted.insert(name.clone(), value.clone());
}
let mut names: Vec<String> = seed.iter().map(|(name, _)| name.clone()).collect();
let rungs: Vec<RowRung> = binds
.iter()
.map(|(name, _)| {
push_bind_name(&mut names, Some(name));
RowRung::from_names(&names)
})
.collect();
let stamped: Vec<Row> = (0..3)
.map(|_| {
let mut row = Row::new();
for (name, value) in &seed {
row.insert(name.clone(), value.clone());
}
for ((_, value), rung) in binds.iter().zip(&rungs) {
row.stamp(rung, [value.clone()]);
}
row
})
.collect();
for row in &stamped {
prop_assert_eq!(
row.keys().cloned().collect::<Vec<_>>(),
inserted.keys().cloned().collect::<Vec<_>>()
);
prop_assert_eq!(row.values(), inserted.values());
for (name, value) in inserted.iter() {
prop_assert_eq!(row.get(name), Some(value));
}
}
let shared = stamped[0].schema_ptr();
prop_assert!(stamped.iter().all(|row| row.schema_ptr() == shared));
}
}
}