pulsar_utils/
id.rs

1// Copyright (C) 2024 Ethan Uppal. All rights reserved.
2use lazy_static::lazy_static;
3use std::{collections::HashMap, sync::Mutex};
4
5pub type Id = i64;
6
7pub struct Gen {
8    id_map: Mutex<HashMap<&'static str, Id>>
9}
10
11lazy_static! {
12    static ref GEN_SINGLETON: Gen = Gen {
13        id_map: Mutex::new(HashMap::new())
14    };
15}
16
17impl Gen {
18    /// Returns an identifier unique among all [`Gen::next`] calls with the same
19    /// argument `name`.
20    pub fn next(name: &'static str) -> Id {
21        let mut id_map = GEN_SINGLETON.id_map.lock().unwrap();
22        if let Some(id) = id_map.get_mut(&name) {
23            let result = *id;
24            *id += 1;
25            result
26        } else {
27            id_map.insert(name, 1);
28            0
29        }
30    }
31}