sim_table_hash/backend.rs
1//! Library registration for the hash-map table backend: the [`HashBackend`]
2//! `TableBackend` implementation, the [`HashTableLib`] manifest, and the
3//! [`install_hash_table_lib`] entry point.
4
5use std::sync::Arc;
6
7use sim_kernel::{Cx, Lib, LibManifest, Linker, Result, Symbol, TableBackend, Value};
8
9use crate::HashTable;
10
11/// Table backend that constructs [`HashTable`] objects for the `hash` backend
12/// name.
13///
14/// Registered with the context table registry by [`install_hash_table_lib`] so
15/// that table operations resolved against the `hash` backend build hash-map
16/// tables.
17pub struct HashBackend;
18
19impl TableBackend for HashBackend {
20 fn name(&self) -> &str {
21 "hash"
22 }
23
24 fn new_table(&self, cx: &mut Cx, entries: Vec<(Symbol, Value)>) -> Result<Value> {
25 cx.factory()
26 .opaque(Arc::new(HashTable::with_entries(entries)))
27 }
28}
29
30/// Loadable library manifest for the hash table backend.
31///
32/// Declares the `table/hash` library identity and ABI; backend registration is
33/// performed separately by [`install_hash_table_lib`].
34pub struct HashTableLib;
35
36impl Lib for HashTableLib {
37 fn manifest(&self) -> LibManifest {
38 sim_table_core::backend_manifest(
39 Symbol::qualified("table", "hash"),
40 env!("CARGO_PKG_VERSION"),
41 )
42 }
43
44 fn load(&self, _cx: &mut sim_kernel::LoadCx, _linker: &mut Linker<'_>) -> Result<()> {
45 Ok(())
46 }
47}
48
49/// Register the [`HashBackend`] and load the [`HashTableLib`] into `cx`.
50///
51/// Idempotent: if the `table/hash` library is already present the call is a
52/// no-op. After installation the `hash` backend can be selected as the active
53/// table backend via the context table registry.
54pub fn install_hash_table_lib(cx: &mut Cx) -> Result<()> {
55 if cx
56 .registry()
57 .lib(&Symbol::qualified("table", "hash"))
58 .is_some()
59 {
60 return Ok(());
61 }
62 cx.table_registry_mut().register(Arc::new(HashBackend));
63 cx.load_lib(&HashTableLib).map(|_| ())
64}