Files
ecs/ecs/idmap.sakura
T
2026-10-30 09:55:40 -05:00

93 lines
2.5 KiB
Plaintext

#! Contains `idmap`, the table of numbers by 64-bit keys that a world looks
#! things up in on every call: a type of component by its key, a table by the
#! hash of its components, an edge between tables, and a query by what it asks.
module ecs;
# Numbers by 64-bit keys, held open: a key's place is its hash, or the first
# empty one after it, so a lookup reads one or two places of one array. Keys
# are never 0, which marks a place empty, and nothing is ever taken out.
struct idmap : owning {
var keys: *mut u64;
var values: *mut u32;
var capacity: u64; # A power of two, or 0.
var count: u64;
var shift: u64; # 64 less the bits of the capacity.
}
# What `get` gives for a key it doesn't hold.
const absent: u32 = 0xFFFFFFFF;
def idmap::new(): idmap {
return idmap{};
}
# The key as held: 0 is taken for another, as 0 marks a place empty.
def idmap::held(key: u64): u64 {
return key == 0 ? 0x9E3779B97F4A7C15 : key;
}
def idmap::get(&this, key: u64): u32 {
return absent if this.capacity == 0;
val k := idmap::held(key);
var at := (k * 0x9E3779B97F4A7C15) >> this.shift;
while true {
val there := this.keys[at];
return this.values[at] if there == k;
return absent if there == 0;
at = (at + 1) & (this.capacity - 1);
}
return absent;
}
def idmap::set(&mut this, key: u64, value: u32): void {
if (this.count + 1) * 2 > this.capacity {
this.grow();
}
val k := idmap::held(key);
var at := (k * 0x9E3779B97F4A7C15) >> this.shift;
while true {
val there := this.keys[at];
if there == k {
this.values[at] = value;
return;
}
if there == 0 {
this.keys[at] = k;
this.values[at] = value;
this.count++;
return;
}
at = (at + 1) & (this.capacity - 1);
}
}
def idmap::grow(&mut this): void {
val old_keys := this.keys;
val old_values := this.values;
val old := this.capacity;
this.capacity = old == 0 ? 16 : old * 2;
var bits := 0u;
while (1u << bits) < this.capacity { bits++; }
this.shift = 64 - bits;
this.keys = raw_allocate_zeroed(this.capacity * 8) as *mut u64;
this.values = raw_allocate(this.capacity * 4) as *mut u32;
this.count = 0;
for i in 0..old {
if old_keys[i] != 0 {
this.set(old_keys[i], old_values[i]);
}
}
raw_release(old_keys as *mut u8);
raw_release(old_values as *mut u8);
}
pub def idmap::close(&mut this): void {
raw_release(this.keys as *mut u8);
raw_release(this.values as *mut u8);
this.keys = null;
this.values = null;
this.capacity = 0;
this.count = 0;
}