use std::rc::Rc;
use crate::{RecomposeScope, SlotsHost, collections::map::HashMap, scope_order::ScopeOrder};
#[derive(Default)]
pub(super) struct ScopeGroups {
hosts: Vec<(Rc<SlotsHost>, usize)>,
by_key: HashMap<usize, usize>,
order: ScopeOrder,
}
impl ScopeGroups {
pub(super) fn group(
&mut self,
scopes: &mut Vec<RecomposeScope>,
mut host_of: impl FnMut(&RecomposeScope) -> Rc<SlotsHost>,
) {
self.hosts.clear();
let Some(first) = scopes.first() else {
return;
};
let first_identity = first.slots_host_identity();
if scopes
.iter()
.all(|scope| scope.slots_host_identity() == first_identity)
{
self.hosts.push((host_of(first), scopes.len()));
return;
}
let (hosts, by_key) = (&mut self.hosts, &mut self.by_key);
let mut previous = None;
self.order.order_by(scopes, |scope| {
let identity = scope.slots_host_identity();
match previous {
Some((previous_identity, group)) if previous_identity == identity => group,
_ => {
let host = host_of(scope);
let next = hosts.len();
let group = *by_key.entry(host.storage_key()).or_insert(next);
if group == next {
hosts.push((host, 0));
}
previous = Some((identity, group));
group
}
}
});
self.by_key.clear();
for ((_, end), &placed_end) in self.hosts.iter_mut().zip(self.order.ends()) {
*end = placed_end;
}
}
pub(super) fn iter(&self) -> impl Iterator<Item = (&Rc<SlotsHost>, std::ops::Range<usize>)> {
let mut start = 0;
self.hosts.iter().map(move |(host, end)| {
let range = start..*end;
start = *end;
(host, range)
})
}
pub(super) fn clear(&mut self) {
self.hosts.clear();
}
}