Skip to main content

substrate_data/model/atom/
local.rs

1//! The table a process keeps itself: the runtime's, or a tool's.
2use std::collections::HashMap;
3
4use crate::sync::{OnceLock, RwLock};
5
6#[derive(Default)]
7struct Names {
8    numbers: HashMap<&'static str, u32>,
9    names: Vec<&'static str>,
10}
11
12static NAMES: OnceLock<RwLock<Names>> = OnceLock::new();
13
14fn names() -> &'static RwLock<Names> {
15    NAMES.get_or_init(Default::default)
16}
17
18/// `name`'s number, made the first time (its text kept for good).
19#[must_use]
20pub fn intern(name: &str) -> u32 {
21    if let Some(&n) = names().read().numbers.get(name) {
22        return n;
23    }
24    let mut t = names().write();
25    if let Some(&n) = t.numbers.get(name) {
26        return n;
27    }
28    let kept: &'static str = Box::leak(name.into());
29    let n = u32::try_from(t.names.len()).unwrap_or(u32::MAX);
30    t.names.push(kept);
31    t.numbers.insert(kept, n);
32    n
33}
34
35/// The name numbered `n`, if there's one.
36#[must_use]
37pub fn name(n: u32) -> Option<&'static str> {
38    names().read().names.get(n as usize).copied()
39}