use std::cell::Cell;
use crate::object::{Object, StringBuilder};
pub(crate) const BYTES_BETWEEN_GC: i64 = 6 * 1024 * 1024;
thread_local! {
static SINCE_GC: Cell<i64> = const { Cell::new(0) };
}
pub(crate) fn count(bytes: i64, kind: &str) {
if bytes == 0 {
return;
}
if crate::object::trace_alloc() {
eprintln!("M {bytes} {kind}");
}
SINCE_GC.with(|since| since.set(since.get() + bytes));
}
pub(crate) fn adjust(bytes: i64, kind: &str) {
if bytes == 0 {
return;
}
if crate::object::trace_alloc() {
eprintln!("M+ {bytes} {kind}");
}
SINCE_GC.with(|since| since.set(since.get() + bytes));
}
pub(crate) fn cell_for(bytes: i64) -> u16 {
[32, 64, 128, 256, 512]
.into_iter()
.find(|&cell| bytes <= i64::from(cell))
.unwrap_or(0)
}
pub(crate) fn realloc(cell: &mut u16, bytes: i64, kind: &str) {
count(bytes, kind);
if *cell != 0 && bytes > i64::from(*cell) {
count(bytes, kind);
*cell = cell_for(bytes);
}
}
pub(crate) fn since_gc() -> i64 {
SINCE_GC.with(Cell::get)
}
pub(crate) fn reset() {
SINCE_GC.with(|since| since.set(0));
}
pub(crate) fn program_object_bytes(superclasses: usize, hash: usize, room: usize) -> i64 {
(40 + 16 * superclasses + 8 * hash + 40 * room) as i64
}
pub(crate) fn vector_bytes(room: usize) -> i64 {
(4 + 5 * room + ((room + 7) & !7)) as i64
}
pub(crate) fn map_bytes(buckets: usize, slots: usize) -> i64 {
(32 + 8 * buckets + 40 * slots) as i64
}
pub(crate) fn string_builder_bytes(buffer: &StringBuilder) -> i64 {
16 + 2 * (i64::from(buffer.room) - 1)
}
pub(crate) fn object_bytes(object: &Object, vector_room: usize) -> i64 {
match object {
Object::Program(obj) | Object::IntClassMod(obj) => obj.heap_bytes(),
Object::String(text) => text.len() as i64 + 2,
Object::List(items) => 2 + 5 * items.len() as i64,
Object::Vector(_) | Object::AnonFn(_) => vector_bytes(vector_room),
Object::IndexedIter { .. } => 21,
Object::MapIter { .. } => 9,
Object::Map(table) => map_bytes(table.bucket_count(), table.slot_count()),
Object::Pattern { .. } => 24,
Object::StringBuilder(buffer) => string_builder_bytes(buffer),
Object::Decimal(big) => 5 + (big.digs.len() as i64 + 1) / 2,
Object::ByteArray(bytes) => 4 + 8 * bytes.len().div_ceil(1 << 28) as i64,
Object::CharSet { name, .. } => 29 + name.len() as i64,
Object::StrComp(comparator) => comparator.heap_bytes(),
Object::GrammarRule(_) => 72,
Object::Dict(_) => 56,
Object::Class(_) => 32,
Object::File(_) => 40,
Object::Date { .. } | Object::TimeZone(_) => 8,
Object::FileName(name) => 18 + name.path.len() as i64,
Object::TempFile(name) => 16 + name.len() as i64,
Object::CompiledCode(func) => {
48 + 2 * (func.obj_refs.len() as i64 - 1).max(0) + 4 + func.code.len() as i64
}
Object::FrameRef(fref) => 104 + 16 * ((fref.nlocals + fref.nparams) as i64 - 1),
Object::FrameDesc(_) => 12,
Object::Opaque { .. } => 0,
}
}