1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
use std::{
collections::HashMap,
fmt,
path::PathBuf,
sync::{
atomic::{AtomicU8, Ordering},
RwLock,
},
};
lazy_static::lazy_static! {
static ref SOURCE_IDS_TO_FILES: RwLock<HashMap<SourceId, (PathBuf, String)>> =
RwLock::new(HashMap::new());
}
static SOURCE_ID_COUNTER: AtomicU8 = AtomicU8::new(1);
#[derive(PartialEq, Eq, Clone, Copy, Hash)]
#[cfg_attr(feature = "span-serialize", derive(serde::Serialize))]
pub struct SourceId(u8);
impl fmt::Debug for SourceId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_fmt(format_args!("SourceId({})", self.0))
}
}
#[cfg(feature = "self-rust-tokenize")]
pub const SPAN_TOKEN_IDENT: &str = "CURRENT_SOURCE_ID";
#[cfg(feature = "self-rust-tokenize")]
impl self_rust_tokenize::SelfRustTokenize for SourceId {
fn append_to_token_stream(
&self,
token_stream: &mut self_rust_tokenize::proc_macro2::TokenStream,
) {
let current_source_id_reference = self_rust_tokenize::proc_macro2::Ident::new(
SPAN_TOKEN_IDENT,
self_rust_tokenize::proc_macro2::Span::call_site(),
);
self_rust_tokenize::TokenStreamExt::append(token_stream, current_source_id_reference);
}
}
impl SourceId {
pub fn new(path: PathBuf, content: String) -> Self {
let source_id = Self(SOURCE_ID_COUNTER.fetch_add(1, Ordering::SeqCst));
SOURCE_IDS_TO_FILES
.write()
.unwrap()
.insert(source_id, (path, content));
source_id
}
pub const NULL: Self = Self(0);
pub const fn is_null(&self) -> bool {
self.0 == 0
}
pub fn get_file(&self) -> Option<(PathBuf, String)> {
SOURCE_IDS_TO_FILES.read().unwrap().get(self).cloned()
}
pub fn get_file_slice<I: std::slice::SliceIndex<str>>(
&self,
slice: I,
) -> Option<(PathBuf, <I::Output as ToOwned>::Owned)>
where
I::Output: Sized + ToOwned,
{
if let Some((path_buf, string)) = SOURCE_IDS_TO_FILES.read().unwrap().get(self) {
string
.get(slice)
.map(|slice| (path_buf.clone(), slice.to_owned()))
} else {
None
}
}
#[doc(hidden)]
pub fn get_count(&self) -> u8 {
self.0
}
pub fn drop_handle(self) {
SOURCE_IDS_TO_FILES.write().unwrap().remove(&self);
}
}