qualname 0.0.2

Support for XML Namespaces Qualified Name
Documentation
use std::{
    hash::{Hash, Hasher},
    sync::{LazyLock, RwLock},
};

// Using a Vec as an arena allocator.
// The Option indicates whether a slot is in use. When the reference count drops to zero, the entry is replaced with None.
#[derive(Clone, Debug)]
struct RefString {
    s: String,
    refs: usize,
}
impl RefString {
    pub fn new(s: String) -> Self {
        RefString { s, refs: 1 }
    }
}
static UNIQUE_STRINGS: LazyLock<RwLock<Vec<Option<RefString>>>> =
    LazyLock::new(|| RwLock::new(Vec::new()));

fn get(value: &str) -> UniqueString {
    // Scan the Vec to find this string
    // If found then return its index.
    // Otherwise append a new entry
    let mut attempt = 0;
    loop {
        attempt += 1;
        if attempt > 10 {
            panic!("too many attempts")
        }
        if let Ok(mut hs) = UNIQUE_STRINGS.write() {
            if let Some((i, _)) = hs
                .iter_mut()
                .enumerate()
                .find(|(_, e)| e.as_ref().is_some_and(|f| f.s == value))
            {
                // i is the index into the arena allocator
                if let Some(g) = hs[i].iter_mut().next() {
                    g.refs += 1;
                }
                return UniqueString(i);
            } else {
                // Append a new entry
                hs.push(Some(RefString::new(String::from(value))));
                return UniqueString(hs.len() - 1);
            }
        }
    }
}

static EMPTY_STRING: LazyLock<UniqueString> = LazyLock::new(|| get(""));

/// A string that is globally unique at runtime.
/// Any equal `UniqueString` will use the same memory.
/// Comparing two `UniqueString` is fast because only the index
/// needs to be compared.
#[derive(PartialEq, Eq, Debug)]
pub(crate) struct UniqueString(pub usize);
impl UniqueString {
    pub fn empty() -> Self {
        EMPTY_STRING.clone()
    }
    pub fn to_string(&self) -> String {
        let mut cnt = 0;
        loop {
            cnt += 1;
            if cnt > 1000 {
                panic!("too many iterations (us::to_string)")
            }
            if let Ok(hs) = UNIQUE_STRINGS.read() {
                if let Some(us) = &hs[self.0] {
                    break us.s.clone();
                } else {
                    panic!("accessing an invalid UniqueString (to_string)")
                }
            }
        }
    }
    #[cfg(test)]
    pub fn count() -> usize {
        let mut cnt = 0;
        loop {
            cnt += 1;
            if cnt > 1000 {
                panic!("too many iterations (us::count)")
            }
            if let Ok(hs) = UNIQUE_STRINGS.read() {
                break hs.iter().filter(|us| us.is_some()).count();
            }
        }
    }
}
/// Increment the reference count when cloned.
impl Clone for UniqueString {
    fn clone(&self) -> Self {
        let mut attempt = 0;
        loop {
            attempt += 1;
            if attempt > 10 {
                panic!("too many attempts")
            }
            if let Ok(mut hs) = UNIQUE_STRINGS.write() {
                if let Some(g) = hs[self.0].iter_mut().next() {
                    g.refs += 1;
                }
                return UniqueString(self.0);
            }
        }
    }
}
impl PartialEq<String> for UniqueString {
    fn eq(&self, other: &String) -> bool {
        self.to_string().eq(other)
    }
}
impl PartialEq<str> for UniqueString {
    fn eq(&self, other: &str) -> bool {
        self.to_string().eq(other)
    }
}
impl Hash for UniqueString {
    fn hash<H: Hasher>(&self, state: &mut H) {
        let mut cnt = 0;
        loop {
            cnt += 1;
            if cnt > 1000 {
                panic!("too many iterations (us::hash)")
            }
            if let Ok(hs) = UNIQUE_STRINGS.read() {
                if let Some(us) = &hs[self.0] {
                    break us.s.hash(state);
                } else {
                    panic!("accessing an invalid UniqueString (hash)")
                }
            }
        }
    }
}

impl From<&str> for UniqueString {
    fn from(value: &str) -> Self {
        get(value)
    }
}
impl Drop for UniqueString {
    fn drop(&mut self) {
        let mut cnt = 0;
        loop {
            cnt += 1;
            if cnt > 10 {
                panic!("too many iterations (us::drop)")
            }
            match UNIQUE_STRINGS.write() {
                Ok(mut hs) => {
                    if hs[self.0].as_ref().is_some_and(|e| e.refs == 1) {
                        // This was the last reference
                        hs[self.0].take();
                    } else {
                        // Still more references
                        if let Some(g) = hs[self.0].iter_mut().next() {
                            g.refs -= 1;
                        } else {
                            // Already been dropped
                        }
                    }
                    return;
                }
                Err(_e) => (), //eprintln!("unable to obtain write lock due to {:?}", e),
            }
        }
    }
}

#[cfg(test)]
pub(crate) fn run_sequential_test(f: impl Fn() -> ()) {
    static TEST_LOCK: RwLock<()> = RwLock::new(());
    let _lock = TEST_LOCK.write().unwrap_or_else(|e| e.into_inner());
    f();
}

#[test]
fn test_add_and_drop() {
    run_sequential_test(|| {
        let initial_count = UniqueString::count();
        let s = UniqueString::from("test_add_and_drop");
        assert_eq!(UniqueString::count(), initial_count + 1);
        drop(s);
        let after_count = UniqueString::count();
        assert_eq!(after_count, initial_count);
    });
}

#[test]
fn test_add_clone_and_drop() {
    run_sequential_test(|| {
        let initial_count = UniqueString::count();
        let s1 = UniqueString::from("test_add_clone_and_drop");
        assert_eq!(UniqueString::count(), initial_count + 1);
        let s2 = UniqueString::from("test_add_clone_and_drop");
        assert_eq!(UniqueString::count(), initial_count + 1);
        drop(s1);
        assert_eq!(UniqueString::count(), initial_count + 1);
        drop(s2);
        assert_eq!(UniqueString::count(), initial_count);
    });
}

/**
 * Run two other tests many times in separate threads to
 * detect possible race conditions.
 */

#[test]
fn test_multi_100() {
    run_sequential_test(|| {
        for _i in 0..100 {
            let s1 = UniqueString::from("ok");
            let s2 = UniqueString::from("ok");
            assert_eq!(s1, s2);
        }
    })
}