makepad_draw/text/
intern.rs1use std::{
2 collections::HashSet,
3 sync::{Arc, Mutex, OnceLock},
4};
5
6pub trait Intern {
7 fn intern(&self) -> Arc<str>;
8}
9
10impl Intern for str {
11 fn intern(&self) -> Arc<str> {
12 INTERNER
13 .get_or_init(|| Mutex::new(Interner::new()))
14 .lock()
15 .unwrap()
16 .intern(self)
17 }
18}
19
20static INTERNER: OnceLock<Mutex<Interner>> = OnceLock::new();
21
22#[derive(Debug)]
23struct Interner {
24 cached_strings: HashSet<Arc<str>>,
25}
26
27impl Interner {
28 fn new() -> Self {
29 Self {
30 cached_strings: HashSet::new(),
31 }
32 }
33
34 fn intern(&mut self, string: &str) -> Arc<str> {
35 if !self.cached_strings.contains(string) {
36 self.cached_strings.insert(string.into());
37 }
38 self.cached_strings.get(string).unwrap().clone()
39 }
40}