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