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

66 lines
1.5 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, Option<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
.entry(path.to_owned())
.or_insert_with(|| {
self.content(path).map(|content| {
let hash = blake3::hash(&content).to_hex();
format!("b3-{}", &hash[0..8])
})
})
.clone()
}
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)
}
}