Skip to main content

harn_vm/
builtin_id.rs

1use std::fmt;
2
3/// Compact, deterministic identifier for a builtin name.
4///
5/// The VM keeps name-keyed builtin maps as the authoritative registry for
6/// dynamic calls and diagnostics. Hot direct-call bytecode can use this ID to
7/// hit the side index without repeating string-keyed map lookups.
8#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
9pub struct BuiltinId(u64);
10
11impl BuiltinId {
12    pub const fn from_name(name: &str) -> Self {
13        // FNV-1a 64-bit. Stable across processes and cheap enough for compile
14        // and registration time.
15        let bytes = name.as_bytes();
16        let mut hash = 0xcbf29ce484222325u64;
17        let mut i = 0;
18        while i < bytes.len() {
19            hash ^= bytes[i] as u64;
20            hash = hash.wrapping_mul(0x100000001b3);
21            i += 1;
22        }
23        Self(hash)
24    }
25
26    pub const fn from_raw(raw: u64) -> Self {
27        Self(raw)
28    }
29
30    pub const fn raw(self) -> u64 {
31        self.0
32    }
33}
34
35impl fmt::Display for BuiltinId {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        write!(f, "{:#018x}", self.0)
38    }
39}