use std::collections::hash_map::Entry;
use std::collections::BTreeMap;
use std::mem::size_of;
use std::sync::Arc;
use relate_core::{Node, PropertyMap, Relationship, Value};
use crate::hash_seed::IdMap;
use super::{
buffer_bytes, created_label_bytes, property_heap, str_logical_bytes, OVERHEAD_MAP_ENTRY,
};
pub(crate) fn row_retained_heap(values: &[Value]) -> u64 {
let mut walk = RowWalk::default();
for value in values {
walk.note_value(value);
}
walk.resolve();
walk.charge()
}
#[cfg(test)]
thread_local! {
static NOTE_OPS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
#[cfg(test)]
pub(crate) fn note_ops() -> u64 {
NOTE_OPS.with(|ops| ops.get())
}
#[cfg(test)]
pub(crate) fn reset_note_ops() {
NOTE_OPS.with(|ops| ops.set(0));
}
#[derive(Clone, Copy)]
enum Expandable<'a> {
Items(&'a Arc<Vec<Value>>),
Entries(&'a Arc<BTreeMap<String, Value>>),
Node(&'a Node),
Rel(&'a Relationship),
Path(&'a relate_core::Path),
}
#[derive(Default)]
struct RowWalk<'a> {
seen: IdMap<usize, RowAllocation>,
expandable: IdMap<usize, Expandable<'a>>,
owned_worklist: Vec<usize>,
}
impl<'a> RowWalk<'a> {
fn note<T: ?Sized>(&mut self, allocation: &Arc<T>, own_bytes: u64) -> (usize, bool) {
#[cfg(test)]
NOTE_OPS.with(|ops| ops.set(ops.get() + 1));
let id = Arc::as_ptr(allocation) as *const () as usize;
let (noted, first) = match self.seen.entry(id) {
Entry::Occupied(entry) => (entry.into_mut(), false),
Entry::Vacant(entry) => (
entry.insert(RowAllocation {
bytes: own_bytes,
holders: Arc::strong_count(allocation) as u64,
row_refs: 0,
}),
true,
),
};
noted.row_refs += 1;
if noted.row_owned() {
self.owned_worklist.push(id);
}
(id, first)
}
fn note_value(&mut self, value: &'a Value) {
match value {
Value::Null
| Value::Bool(_)
| Value::Int(_)
| Value::Float(_)
| Value::Temporal(_)
| Value::Point(_)
| Value::Uuid(_) => {}
Value::String(text) => {
self.note(text, str_logical_bytes(text));
}
Value::Bytes(payload) => {
self.note(payload, relate_core::bytes_logical_bytes(payload));
}
Value::List(items) | Value::Vector { values: items, .. } => {
let (id, first) =
self.note(items, buffer_bytes(items.len(), size_of::<Value>() as u64));
if first {
self.expandable.insert(id, Expandable::Items(items));
}
}
Value::Map(entries) => {
let (id, first) = self.note(entries, 0);
if first {
self.expandable.insert(id, Expandable::Entries(entries));
}
}
Value::Node(node) => {
let (id, first) = self.note(node, size_of::<Node>() as u64);
if first {
self.expandable.insert(id, Expandable::Node(node));
}
}
Value::Relationship(rel) => {
let (id, first) = self.note(
rel,
size_of::<Relationship>() as u64 + str_logical_bytes(&rel.rel_type),
);
if first {
self.expandable.insert(id, Expandable::Rel(rel));
}
}
Value::Path(path) => {
let own = size_of::<relate_core::Path>() as u64
+ buffer_bytes(path.nodes.len(), size_of::<Node>() as u64)
+ buffer_bytes(path.rels.len(), size_of::<Relationship>() as u64);
let (id, first) = self.note(path, own);
if first {
self.expandable.insert(id, Expandable::Path(path));
}
}
}
}
fn resolve(&mut self) {
if self.expandable.is_empty() {
return;
}
while let Some(id) = self.owned_worklist.pop() {
let Some(expandable) = self.expandable.get(&id).copied() else {
continue;
};
match expandable {
Expandable::Items(items) => {
for item in items.iter() {
self.note_value(item);
}
}
Expandable::Entries(entries) => {
for (_, value) in entries.iter() {
self.note_value(value);
}
}
Expandable::Node(node) => self.note_innards(&node.labels, &node.properties),
Expandable::Rel(rel) => self.note_properties(&rel.properties),
Expandable::Path(path) => {
for node in &path.nodes {
self.note_innards(&node.labels, &node.properties);
}
for rel in &path.rels {
self.note_properties(&rel.properties);
}
}
}
}
}
fn note_innards(&mut self, labels: &Arc<Vec<String>>, properties: &Arc<PropertyMap>) {
self.note(labels, created_label_bytes(labels));
self.note_properties(properties);
}
fn note_properties(&mut self, properties: &Arc<PropertyMap>) {
self.note(properties, property_heap(properties));
}
fn charge(self) -> u64 {
let RowWalk {
seen, expandable, ..
} = self;
seen.into_iter()
.map(|(id, allocation)| {
if !allocation.row_owned() {
return 0;
}
match expandable.get(&id) {
Some(Expandable::Entries(entries)) => {
allocation.bytes + map_key_figure(entries)
}
Some(Expandable::Path(path)) => allocation.bytes + path_rel_type_figure(path),
_ => allocation.bytes,
}
})
.sum()
}
}
fn map_key_figure(entries: &Arc<BTreeMap<String, Value>>) -> u64 {
#[cfg(test)]
NOTE_OPS.with(|ops| ops.set(ops.get() + 1));
entries
.keys()
.map(|key| OVERHEAD_MAP_ENTRY + str_logical_bytes(key))
.sum()
}
fn path_rel_type_figure(path: &relate_core::Path) -> u64 {
#[cfg(test)]
NOTE_OPS.with(|ops| ops.set(ops.get() + 1));
path.rels
.iter()
.map(|rel| str_logical_bytes(&rel.rel_type))
.sum()
}
struct RowAllocation {
bytes: u64,
holders: u64,
row_refs: u64,
}
impl RowAllocation {
fn row_owned(&self) -> bool {
self.row_refs == self.holders
}
}