use std::{borrow::Borrow, cmp::Ord, path::Path};
use rpds::RedBlackTreeMapSync;
use tinymist_std::ImmutPath;
use typst::diag::FileResult;
use crate::{AccessModel, Bytes, FileId, FileSnapshot, PathAccessModel};
#[derive(Default, Debug, Clone)]
pub struct OverlayAccessModel<K: Ord, M> {
files: RedBlackTreeMapSync<K, FileSnapshot>,
pub inner: M,
}
impl<K: Ord + Clone, M> OverlayAccessModel<K, M> {
pub fn new(inner: M) -> Self {
Self {
files: RedBlackTreeMapSync::default(),
inner,
}
}
pub fn inner(&self) -> &M {
&self.inner
}
pub fn inner_mut(&mut self) -> &mut M {
&mut self.inner
}
pub fn clear_shadow(&mut self) {
self.files = RedBlackTreeMapSync::default();
}
pub fn file_paths(&self) -> Vec<K> {
self.files.keys().cloned().collect()
}
pub fn add_file<Q: Ord + ?Sized>(
&mut self,
path: &Q,
snap: FileSnapshot,
cast: impl Fn(&Q) -> K,
) where
K: Borrow<Q>,
{
match self.files.get_mut(path) {
Some(e) => {
*e = snap;
}
None => {
self.files.insert_mut(cast(path), snap);
}
}
}
pub fn remove_file<Q: Ord + ?Sized>(&mut self, path: &Q)
where
K: Borrow<Q>,
{
self.files.remove_mut(path);
}
}
impl<M: PathAccessModel> PathAccessModel for OverlayAccessModel<ImmutPath, M> {
fn content(&self, src: &Path) -> FileResult<Bytes> {
if let Some(content) = self.files.get(src) {
return content.content().cloned();
}
self.inner.content(src)
}
}
impl<M: AccessModel> AccessModel for OverlayAccessModel<FileId, M> {
fn reset(&mut self) {
self.inner.reset();
}
fn content(&self, src: FileId) -> (Option<ImmutPath>, FileResult<Bytes>) {
if let Some(content) = self.files.get(&src) {
return (None, content.content().cloned());
}
self.inner.content(src)
}
}