veryl_parser/
text_table.rs1use crate::resource_table::PathId;
2use std::cell::RefCell;
3use std::collections::HashMap;
4
5#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
6pub struct TextId(pub usize);
7
8thread_local!(static TEXT_ID: RefCell<usize> = const { RefCell::new(0) });
9
10pub fn new_text_id() -> TextId {
11 TEXT_ID.with(|f| {
12 let mut ret = f.borrow_mut();
13 *ret += 1;
14 TextId(*ret)
15 })
16}
17
18#[derive(Clone, Debug)]
19pub struct TextInfo {
20 pub text: String,
21 pub path: PathId,
22}
23
24#[derive(Clone, Default, Debug)]
25pub struct TextTable {
26 current_text: TextId,
27 table: HashMap<TextId, TextInfo>,
28}
29
30impl TextTable {
31 pub fn set_current_text(&mut self, info: TextInfo) -> TextId {
32 let id = new_text_id();
33 self.table.insert(id, info);
34 self.current_text = id;
35 id
36 }
37
38 pub fn get_current_text(&self) -> TextId {
39 self.current_text
40 }
41
42 pub fn get(&self, id: TextId) -> Option<TextInfo> {
43 self.table.get(&id).cloned()
44 }
45
46 pub fn drop(&mut self, id: PathId) {
47 self.table.retain(|_, x| x.path != id);
48 }
49}
50
51thread_local!(static TEXT_TABLE: RefCell<TextTable> = RefCell::new(TextTable::default()));
52
53pub fn set_current_text(info: TextInfo) -> TextId {
54 TEXT_TABLE.with(|f| f.borrow_mut().set_current_text(info))
55}
56
57pub fn get_current_text() -> TextId {
58 TEXT_TABLE.with(|f| f.borrow().get_current_text())
59}
60
61pub fn get(id: TextId) -> Option<TextInfo> {
62 TEXT_TABLE.with(|f| f.borrow().get(id))
63}
64
65pub fn drop(id: PathId) {
66 TEXT_TABLE.with(|f| f.borrow_mut().drop(id))
67}