use std::{
hash::{Hash, Hasher},
sync::{LazyLock, RwLock},
};
#[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 {
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))
{
if let Some(g) = hs[i].iter_mut().next() {
g.refs += 1;
}
return UniqueString(i);
} else {
hs.push(Some(RefString::new(String::from(value))));
return UniqueString(hs.len() - 1);
}
}
}
}
static EMPTY_STRING: LazyLock<UniqueString> = LazyLock::new(|| get(""));
#[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();
}
}
}
}
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) {
hs[self.0].take();
} else {
if let Some(g) = hs[self.0].iter_mut().next() {
g.refs -= 1;
} else {
}
}
return;
}
Err(_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);
});
}
#[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);
}
})
}