Skip to content

Commit 9d2263c

Browse files
committed
perf: cached source rope
1 parent b41064f commit 9d2263c

File tree

1 file changed

+15
-7
lines changed

1 file changed

+15
-7
lines changed

src/cached_source.rs

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ use crate::{
2020
struct CachedData {
2121
hash: OnceLock<u64>,
2222
size: OnceLock<usize>,
23-
source: OnceLock<Vec<&'static str>>,
23+
chunks: OnceLock<Vec<&'static str>>,
2424
columns_map: OnceLock<Option<SourceMap>>,
2525
line_only_map: OnceLock<Option<SourceMap>>,
2626
}
@@ -79,11 +79,9 @@ impl CachedSource {
7979
cache: Arc::new(CachedData::default()),
8080
}
8181
}
82-
}
8382

84-
impl Source for CachedSource {
85-
fn source(&self) -> SourceValue {
86-
let chunks = self.cache.source.get_or_init(|| {
83+
fn get_or_init_chunks(&self) -> &[&str] {
84+
self.cache.chunks.get_or_init(|| {
8785
#[allow(unsafe_code)]
8886
// SAFETY: CachedSource guarantees that the underlying source outlives the cache,
8987
// so transmuting Vec<&str> to Vec<&'static str> is safe in this context.
@@ -93,7 +91,13 @@ impl Source for CachedSource {
9391
self.rope().collect(),
9492
)
9593
}
96-
});
94+
})
95+
}
96+
}
97+
98+
impl Source for CachedSource {
99+
fn source(&self) -> SourceValue {
100+
let chunks = self.get_or_init_chunks();
97101
if chunks.len() == 1 {
98102
return SourceValue::String(Cow::Borrowed(chunks[0]));
99103
}
@@ -105,14 +109,18 @@ impl Source for CachedSource {
105109
}
106110

107111
fn rope(&self) -> Box<dyn Iterator<Item = &str> + '_> {
108-
self.inner.rope()
112+
let chunks = self.get_or_init_chunks();
113+
Box::new(chunks.iter().cloned())
109114
}
110115

111116
fn buffer(&self) -> Cow<[u8]> {
112117
self.inner.buffer()
113118
}
114119

115120
fn size(&self) -> usize {
121+
if let Some(chunks) = self.cache.chunks.get() {
122+
return chunks.iter().map(|chunk| chunk.len()).sum();
123+
}
116124
*self.cache.size.get_or_init(|| self.inner.size())
117125
}
118126

0 commit comments

Comments
 (0)