treehouse/crates/treehouse/src/vfs/content_version_cache.rs

67 lines
1.6 KiB
Rust
Raw Normal View History

use std::fmt::{self, Debug};
use dashmap::DashMap;
use super::{Dir, DirEntry, EditPath, ImageSize, VPath, VPathBuf};
pub struct Blake3ContentVersionCache<T> {
inner: T,
cache: DashMap<VPathBuf, String>,
}
impl<T> Blake3ContentVersionCache<T> {
pub fn new(inner: T) -> Self {
Self {
inner,
cache: DashMap::new(),
}
}
}
impl<T> Dir for Blake3ContentVersionCache<T>
where
T: Dir,
{
fn dir(&self, path: &VPath) -> Vec<DirEntry> {
self.inner.dir(path)
}
fn content(&self, path: &VPath) -> Option<Vec<u8>> {
self.inner.content(path)
}
fn content_version(&self, path: &VPath) -> Option<String> {
self.cache.get(path).map(|x| x.clone()).or_else(|| {
let version = self.inner.content(path).map(|content| {
let hash = blake3::hash(&content).to_hex();
format!("b3-{}", &hash[0..8])
});
if let Some(version) = &version {
self.cache.insert(path.to_owned(), version.clone());
}
version
})
}
fn image_size(&self, path: &VPath) -> Option<ImageSize> {
self.inner.image_size(path)
}
fn anchor(&self, path: &VPath) -> Option<VPathBuf> {
self.inner.anchor(path)
}
fn edit_path(&self, path: &VPath) -> Option<EditPath> {
self.inner.edit_path(path)
}
}
impl<T> fmt::Debug for Blake3ContentVersionCache<T>
where
T: Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Blake3ContentVersionCache({:?})", self.inner)
}
}