use std::rc::Rc;
use cranpose_core::{NodeId, collections::growth_slack::GrowthSlack};
use cranpose_ui_graphics::{CommandRecording, FxHashMap};
use crate::graph::DrawCommandId;
#[derive(Default)]
pub(crate) struct Recordings {
slots: FxHashMap<RecorderKey, RecorderSlot>,
update: u64,
}
struct RecorderSlot {
update: u64,
handles: [Option<Rc<CommandRecording>>; 3],
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
struct RecorderKey {
node_id: NodeId,
command_index: u32,
}
impl From<DrawCommandId> for RecorderKey {
fn from(id: DrawCommandId) -> Self {
Self {
node_id: id.node_id,
command_index: id.command_index,
}
}
}
impl RecorderSlot {
fn lend(&mut self) -> Rc<CommandRecording> {
let free = |handle: &Option<Rc<CommandRecording>>| {
handle.as_ref().is_some_and(|recording| {
Rc::strong_count(recording) == 1 && Rc::weak_count(recording) == 0
})
};
let unshared = self.handles.iter().position(|handle| {
free(handle)
&& handle
.as_ref()
.is_some_and(|recording| !recording.shares_shapes())
});
let at = unshared.or_else(|| {
(self.handles.iter().all(Option::is_some) && free(&self.handles[2])).then_some(2)
});
at.and_then(|at| self.handles[at].take())
.unwrap_or_default()
}
fn hold(&mut self, update: u64, recording: &Rc<CommandRecording>) {
self.update = update;
if (self.handles.iter().flatten()).any(|held| Rc::ptr_eq(held, recording)) {
return;
}
self.handles[2] = self.handles[1].take();
self.handles[1] = self.handles[0].take();
self.handles[0] = Some(Rc::clone(recording));
}
}
impl Recordings {
pub(super) fn begin_update(&mut self) {
self.update = self.update.wrapping_add(1);
if self.update.is_multiple_of(512) {
self.sweep();
}
}
#[cold]
#[inline(never)]
fn sweep(&mut self) {
let update = self.update;
self.slots
.retain(|_, slot| update.wrapping_sub(slot.update) <= 64);
}
pub(super) fn trim(&mut self, draws: impl Fn(NodeId) -> bool) {
self.slots.retain(|key, _| draws(key.node_id));
self.slots.trim_growth_slack();
}
pub(super) fn heap_bytes(&self) -> usize {
let table = self.slots.capacity() * (size_of::<(RecorderKey, RecorderSlot)>() + 1);
let kept = self
.slots
.values()
.flat_map(|slot| slot.handles.iter().flatten())
.filter(|recording| Rc::strong_count(recording) == 1)
.map(|recording| recording.pod_heap_bytes() + size_of_val(recording.others()))
.sum::<usize>();
table + kept
}
pub(crate) fn record<T>(
&mut self,
id: DrawCommandId,
record: impl FnOnce(
&mut dyn FnMut() -> Rc<CommandRecording>,
) -> Option<(Rc<CommandRecording>, T)>,
) -> Option<(Rc<CommandRecording>, T)> {
let update = self.update;
let mut slot = self.slots.get_mut(&RecorderKey::from(id));
let made = record(&mut || {
slot.as_deref_mut().map_or_else(Rc::default, |slot| {
slot.update = update;
slot.lend()
})
})?;
Some(made)
}
pub(super) fn keep(&mut self, id: DrawCommandId, recording: &Rc<CommandRecording>) {
let update = self.update;
self.slots
.entry(RecorderKey::from(id))
.or_insert_with(|| RecorderSlot {
update,
handles: [None, None, None],
})
.hold(update, recording);
}
}