Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 1 addition & 72 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ serde = { version = "1.0.216", features = ["derive", "rc"] }
serde_json = "1.0.133"
dyn-clone = "1.0.17"
rustc-hash = "2.1.0"
dashmap = "6.1.0"
memchr = "2.7.4"
itertools = "0.13"

Expand Down
109 changes: 57 additions & 52 deletions src/cached_source.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
use std::{
borrow::Cow,
hash::{BuildHasherDefault, Hash, Hasher},
hash::{Hash, Hasher},
sync::{Arc, OnceLock},
};

use dashmap::{mapref::entry::Entry, DashMap};
use rustc_hash::FxHasher;

use crate::{
Expand All @@ -13,9 +12,16 @@ use crate::{
stream_chunks_of_source_map, StreamChunks,
},
rope::Rope,
MapOptions, Source, SourceMap,
BoxSource, MapOptions, Source, SourceExt, SourceMap,
};

#[derive(Default)]
struct CachedData {
hash: OnceLock<u64>,
line_only_map: OnceLock<Option<SourceMap>>,
columns_map: OnceLock<Option<SourceMap>>,
}

/// It tries to reused cached results from other methods to avoid calculations,
/// usually used after modify is finished.
///
Expand Down Expand Up @@ -49,30 +55,30 @@ use crate::{
/// "Hello World\nconsole.log('test');\nconsole.log('test2');\nHello2\n"
/// );
/// ```
pub struct CachedSource<T> {
inner: Arc<T>,
cached_hash: Arc<OnceLock<u64>>,
cached_maps:
Arc<DashMap<MapOptions, Option<SourceMap>, BuildHasherDefault<FxHasher>>>,
pub struct CachedSource {
inner: BoxSource,
cache: Arc<CachedData>,
}

impl<T> CachedSource<T> {
impl CachedSource {
/// Create a [CachedSource] with the original [Source].
pub fn new(inner: T) -> Self {
Self {
inner: Arc::new(inner),
cached_hash: Default::default(),
cached_maps: Default::default(),
pub fn new<T: SourceExt>(inner: T) -> Self {
let box_source = inner.boxed();
// Check if it's already a BoxSource containing a CachedSource
if let Some(cached_source) =
box_source.as_ref().as_any().downcast_ref::<CachedSource>()
{
return cached_source.clone();
}
}

/// Get the original [Source].
pub fn original(&self) -> &T {
&self.inner
Self {
inner: box_source,
cache: Arc::new(CachedData::default()),
}
}
}

impl<T: Source + Hash + PartialEq + Eq + 'static> Source for CachedSource<T> {
impl Source for CachedSource {
fn source(&self) -> Cow<str> {
self.inner.source()
}
Expand All @@ -92,12 +98,18 @@ impl<T: Source + Hash + PartialEq + Eq + 'static> Source for CachedSource<T> {
}

fn map(&self, options: &MapOptions) -> Option<SourceMap> {
if let Some(map) = self.cached_maps.get(options) {
map.clone()
if options.columns {
self
.cache
.columns_map
.get_or_init(|| self.inner.map(options))
.clone()
} else {
let map = self.inner.map(options);
self.cached_maps.insert(options.clone(), map.clone());
map
self
.cache
.line_only_map
.get_or_init(|| self.inner.map(options))
.clone()
}
}

Expand All @@ -106,29 +118,23 @@ impl<T: Source + Hash + PartialEq + Eq + 'static> Source for CachedSource<T> {
}
}

impl<T: Source + Hash + PartialEq + Eq + 'static> StreamChunks
for CachedSource<T>
{
impl StreamChunks for CachedSource {
fn stream_chunks<'a>(
&'a self,
options: &MapOptions,
on_chunk: crate::helpers::OnChunk<'_, 'a>,
on_source: crate::helpers::OnSource<'_, 'a>,
on_name: crate::helpers::OnName<'_, 'a>,
) -> crate::helpers::GeneratedInfo {
let cached_map = self.cached_maps.entry(options.clone());
match cached_map {
Entry::Occupied(entry) => {
let cell = if options.columns {
&self.cache.columns_map
} else {
&self.cache.line_only_map
};
match cell.get() {
Some(map) => {
let source = self.rope();
if let Some(map) = entry.get() {
#[allow(unsafe_code)]
// SAFETY: We guarantee that once a `SourceMap` is stored in the cache, it will never be removed.
// Therefore, even if we force its lifetime to be longer, the reference remains valid.
// This is based on the following assumptions:
// 1. `SourceMap` will be valid for the entire duration of the application.
// 2. The cached `SourceMap` will not be manually removed or replaced, ensuring the reference's safety.
let map =
unsafe { std::mem::transmute::<&SourceMap, &'a SourceMap>(map) };
if let Some(map) = map {
stream_chunks_of_source_map(
source, map, on_chunk, on_source, on_name, options,
)
Expand All @@ -138,34 +144,33 @@ impl<T: Source + Hash + PartialEq + Eq + 'static> StreamChunks
)
}
}
Entry::Vacant(entry) => {
None => {
let (generated_info, map) = stream_and_get_source_and_map(
&self.inner as &T,
&self.inner,
options,
on_chunk,
on_source,
on_name,
);
entry.insert(map);
cell.get_or_init(|| map);
generated_info
}
}
}
}

impl<T> Clone for CachedSource<T> {
impl Clone for CachedSource {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
cached_hash: self.cached_hash.clone(),
cached_maps: self.cached_maps.clone(),
cache: self.cache.clone(),
}
}
}

impl<T: Source + Hash + PartialEq + Eq + 'static> Hash for CachedSource<T> {
impl Hash for CachedSource {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
(self.cached_hash.get_or_init(|| {
(self.cache.hash.get_or_init(|| {
let mut hasher = FxHasher::default();
self.inner.hash(&mut hasher);
hasher.finish()
Expand All @@ -174,15 +179,15 @@ impl<T: Source + Hash + PartialEq + Eq + 'static> Hash for CachedSource<T> {
}
}

impl<T: PartialEq> PartialEq for CachedSource<T> {
impl PartialEq for CachedSource {
fn eq(&self, other: &Self) -> bool {
self.inner == other.inner
self.inner.as_ref() == other.inner.as_ref()
}
}

impl<T: Eq> Eq for CachedSource<T> {}
impl Eq for CachedSource {}

impl<T: std::fmt::Debug> std::fmt::Debug for CachedSource<T> {
impl std::fmt::Debug for CachedSource {
fn fmt(
&self,
f: &mut std::fmt::Formatter<'_>,
Expand Down Expand Up @@ -244,7 +249,7 @@ mod tests {
source.map(&map_options);

assert_eq!(
*clone.cached_maps.get(&map_options).unwrap().value(),
*clone.cache.columns_map.get().unwrap(),
source.map(&map_options)
);
}
Expand Down
Loading