use std::{borrow::Borrow, marker::PhantomData, num::NonZeroU16, path::Path};
use rpds::RedBlackTreeMapSync;
use tinymist_std::ImmutPath;
use typst::diag::FileResult;
use crate::{AccessModel, Bytes, FileId, FileSnapshot, PathAccessModel};
pub(crate) type RawFileId = NonZeroU16;
#[derive(Default, Debug, Clone)]
pub struct OverlayAccessModel<K, M, S = K>
where
S: Ord,
{
files: RedBlackTreeMapSync<S, FileSnapshot>,
pub inner: M,
_key: PhantomData<fn() -> K>,
}
impl<K, M, S> OverlayAccessModel<K, M, S>
where
S: Ord,
{
pub fn new(inner: M) -> Self {
Self {
files: RedBlackTreeMapSync::default(),
inner,
_key: PhantomData,
}
}
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();
}
}
impl<M> OverlayAccessModel<ImmutPath, M> {
pub fn file_paths(&self) -> Vec<ImmutPath> {
self.files.keys().cloned().collect()
}
pub fn add_file<Q: Ord + ?Sized>(
&mut self,
path: &Q,
snap: FileSnapshot,
cast: impl Fn(&Q) -> ImmutPath,
) where
ImmutPath: 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
ImmutPath: Borrow<Q>,
{
self.files.remove_mut(path);
}
}
impl<M> OverlayAccessModel<FileId, M, RawFileId> {
pub fn file_paths(&self) -> Vec<FileId> {
self.files.keys().copied().map(FileId::from_raw).collect()
}
pub fn add_file(&mut self, id: &FileId, snap: FileSnapshot, cast: impl Fn(&FileId) -> FileId) {
match self.files.get_mut(&id.into_raw()) {
Some(e) => {
*e = snap;
}
None => {
self.files.insert_mut(cast(id).into_raw(), snap);
}
}
}
pub fn remove_file(&mut self, id: &FileId) {
self.files.remove_mut(&id.into_raw());
}
}
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, RawFileId> {
fn reset(&mut self) {
self.inner.reset();
}
fn content(&self, src: FileId) -> (Option<ImmutPath>, FileResult<Bytes>) {
if let Some(content) = self.files.get(&src.into_raw()) {
return (None, content.content().cloned());
}
self.inner.content(src)
}
}