use std::collections::{BTreeMap, HashMap};
use std::mem::size_of;
use std::sync::Arc;
use relate_core::{Node, PropertyMap, Relationship, Value};
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, None);
}
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: HashMap<usize, RowAllocation>,
expandable: HashMap<usize, Expandable<'a>>,
edges: Vec<(usize, usize)>,
applied: Vec<bool>,
owned_worklist: Vec<usize>,
}
impl<'a> RowWalk<'a> {
fn note<T: ?Sized>(
&mut self,
allocation: &Arc<T>,
own_bytes: u64,
from_slot: bool,
) -> (usize, bool) {
#[cfg(test)]
NOTE_OPS.with(|ops| ops.set(ops.get() + 1));
let id = Arc::as_ptr(allocation) as *const () as usize;
match self.seen.get_mut(&id) {
Some(allocation) => {
if from_slot {
allocation.row_refs += 1;
}
(id, false)
}
None => {
self.seen.insert(
id,
RowAllocation {
bytes: own_bytes,
holders: Arc::strong_count(allocation) as u64,
row_refs: u64::from(from_slot),
expanded: false,
outgoing: Vec::new(),
},
);
(id, true)
}
}
}
fn link_edge(&mut self, parent: usize, child: usize) {
let edge = self.edges.len();
self.edges.push((parent, child));
self.applied.push(false);
self.seen
.get_mut(&parent)
.expect("the parent was noted before its children")
.outgoing
.push(edge);
}
fn note_value(&mut self, value: &'a Value, parent: Option<usize>) {
let link = |walk: &mut RowWalk<'a>, id: usize, parent: Option<usize>| {
if let Some(parent) = parent {
walk.link_edge(parent, id);
}
};
match value {
Value::Null
| Value::Bool(_)
| Value::Int(_)
| Value::Float(_)
| Value::Temporal(_)
| Value::Point(_)
| Value::Uuid(_) => {}
Value::String(text) => {
let (id, _) = self.note(text, str_logical_bytes(text), parent.is_none());
link(self, id, parent);
}
Value::Bytes(payload) => {
let (id, _) = self.note(
payload,
relate_core::bytes_logical_bytes(payload),
parent.is_none(),
);
link(self, id, parent);
}
Value::List(items) | Value::Vector { values: items, .. } => {
let (id, first) = self.note(
items,
buffer_bytes(items.len(), size_of::<Value>() as u64),
parent.is_none(),
);
link(self, id, parent);
if first {
self.expandable.insert(id, Expandable::Items(items));
}
}
Value::Map(entries) => {
let (id, first) = self.note(entries, 0, parent.is_none());
link(self, id, parent);
if first {
self.expandable.insert(id, Expandable::Entries(entries));
}
}
Value::Node(node) => {
let (id, first) = self.note(node, size_of::<Node>() as u64, parent.is_none());
link(self, id, parent);
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),
parent.is_none(),
);
link(self, id, parent);
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, parent.is_none());
link(self, id, parent);
if first {
self.expandable.insert(id, Expandable::Path(path));
}
}
}
}
fn resolve(&mut self) {
if self.edges.is_empty() && self.expandable.is_empty() {
return;
}
self.owned_worklist = self
.seen
.iter()
.filter(|(_, allocation)| allocation.row_owned())
.map(|(id, _)| *id)
.collect();
while let Some(id) = self.owned_worklist.pop() {
if !self.seen[&id].expanded {
if let Some(expandable) = self.expandable.get(&id).copied() {
self.seen.get_mut(&id).expect("just popped").expanded = true;
match expandable {
Expandable::Items(items) => {
for item in items.iter() {
self.note_value(item, Some(id));
}
}
Expandable::Entries(entries) => {
for (_, value) in entries.iter() {
self.note_value(value, Some(id));
}
}
Expandable::Node(node) => self.note_innards(
id,
created_label_bytes(&node.labels),
&node.labels,
&node.properties,
),
Expandable::Rel(rel) => self.note_properties(
id,
property_heap(&rel.properties),
&rel.properties,
),
Expandable::Path(path) => {
for node in &path.nodes {
self.note_innards(
id,
created_label_bytes(&node.labels),
&node.labels,
&node.properties,
);
}
for rel in &path.rels {
self.note_properties(
id,
property_heap(&rel.properties),
&rel.properties,
);
}
}
}
}
}
let outgoing =
std::mem::take(&mut self.seen.get_mut(&id).expect("just popped").outgoing);
for edge in outgoing {
if self.applied[edge] {
continue;
}
self.applied[edge] = true;
let child_id = self.edges[edge].1;
let child = self
.seen
.get_mut(&child_id)
.expect("every edge's child was noted before its parent expanded");
child.row_refs += 1;
if child.row_owned() {
self.owned_worklist.push(child_id);
}
}
}
}
fn note_innards(
&mut self,
parent: usize,
label_bytes: u64,
labels: &Arc<Vec<String>>,
properties: &Arc<PropertyMap>,
) {
let (id, _) = self.note(labels, label_bytes, false);
self.link_edge(parent, id);
self.note_properties(parent, property_heap(properties), properties);
}
fn note_properties(&mut self, parent: usize, own_bytes: u64, properties: &Arc<PropertyMap>) {
let (id, _) = self.note(properties, own_bytes, false);
self.link_edge(parent, id);
}
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,
expanded: bool,
outgoing: Vec<usize>,
}
impl RowAllocation {
fn row_owned(&self) -> bool {
self.row_refs == self.holders
}
}