use super::index_allocator::{SimpleIndexAllocator, SlotId};
use super::GcHeapAllocationIndex;
use crate::{GcHeap, GcRuntime, PoolingInstanceAllocatorConfig, Result};
use anyhow::anyhow;
use std::sync::Mutex;
pub struct GcHeapPool {
max_gc_heaps: usize,
index_allocator: SimpleIndexAllocator,
heaps: Mutex<Vec<Option<Box<dyn GcHeap>>>>,
}
impl std::fmt::Debug for GcHeapPool {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("GcHeapPool")
.field("max_gc_heaps", &self.max_gc_heaps)
.field("index_allocator", &self.index_allocator)
.field("heaps", &"..")
.finish()
}
}
impl GcHeapPool {
pub fn new(config: &PoolingInstanceAllocatorConfig) -> Result<Self> {
let index_allocator = SimpleIndexAllocator::new(config.limits.total_gc_heaps);
let max_gc_heaps = usize::try_from(config.limits.total_gc_heaps).unwrap();
let heaps = Mutex::new((0..max_gc_heaps).map(|_| None).collect());
Ok(Self {
max_gc_heaps,
index_allocator,
heaps,
})
}
pub fn is_empty(&self) -> bool {
self.index_allocator.is_empty()
}
pub fn allocate(
&self,
gc_runtime: &dyn GcRuntime,
) -> Result<(GcHeapAllocationIndex, Box<dyn GcHeap>)> {
let allocation_index = self
.index_allocator
.alloc()
.map(|slot| GcHeapAllocationIndex(slot.0))
.ok_or_else(|| {
anyhow!(
"maximum concurrent GC heap limit of {} reached",
self.max_gc_heaps
)
})?;
let heap = match {
let mut heaps = self.heaps.lock().unwrap();
heaps[allocation_index.index()].take()
} {
Some(heap) => heap,
None => gc_runtime.new_gc_heap()?,
};
Ok((allocation_index, heap))
}
pub fn deallocate(&self, allocation_index: GcHeapAllocationIndex, mut heap: Box<dyn GcHeap>) {
heap.reset();
{
let mut heaps = self.heaps.lock().unwrap();
let old_entry = std::mem::replace(&mut heaps[allocation_index.index()], Some(heap));
debug_assert!(old_entry.is_none());
}
self.index_allocator.free(SlotId(allocation_index.0));
}
}