darklua_core/frontend/
work_cache.rs1use std::{
2 collections::HashMap,
3 fmt,
4 path::{Path, PathBuf},
5};
6
7use elsa::FrozenMap;
8
9use crate::{nodes::Block, DarkluaError, Parser, Resources};
10
11use super::DarkluaResult;
12
13pub struct WorkCache<'a> {
14 resources: &'a Resources,
15 input_to_block: FrozenMap<PathBuf, Box<Block>>,
16 input_to_output: HashMap<PathBuf, PathBuf>,
17}
18
19impl<'a> Clone for WorkCache<'a> {
20 fn clone(&self) -> Self {
21 Self {
22 resources: self.resources,
23 input_to_block: Default::default(),
24 input_to_output: self.input_to_output.clone(),
25 }
26 }
27}
28
29impl<'a> fmt::Debug for WorkCache<'a> {
30 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31 f.debug_struct("WorkCache")
32 .field("resources", &self.resources)
33 .field("input_to_output", &self.input_to_output)
34 .finish_non_exhaustive()
35 }
36}
37
38impl<'a> WorkCache<'a> {
39 pub fn new(resources: &'a Resources) -> Self {
40 Self {
41 resources,
42 input_to_block: Default::default(),
43 input_to_output: Default::default(),
44 }
45 }
46
47 pub fn link_source_to_output(
48 &mut self,
49 source: impl Into<PathBuf>,
50 output: impl Into<PathBuf>,
51 ) {
52 self.input_to_output.insert(source.into(), output.into());
53 }
54
55 pub fn contains(&self, source: impl AsRef<Path>) -> bool {
56 self.input_to_output.contains_key(source.as_ref())
57 }
58
59 pub fn get_block(&self, source: impl AsRef<Path>, parser: &Parser) -> DarkluaResult<&Block> {
60 let source = source.as_ref();
61 if let Some(block) = self.input_to_block.get(source) {
62 log::trace!("found cached block for `{}`", source.display());
63 Ok(block)
64 } else {
65 log::trace!("caching block for `{}`", source.display());
66 let block = self.read_block(source, parser)?;
67 Ok(self
68 .input_to_block
69 .insert(source.to_path_buf(), Box::new(block)))
70 }
71 }
72
73 fn read_block(&self, source: &Path, parser: &Parser) -> DarkluaResult<Block> {
74 if let Some(output_path) = self.input_to_output.get(source) {
75 let content = self.resources.get(output_path)?;
76 parser.parse(&content).map_err(|parser_error| {
77 DarkluaError::parser_error(output_path, parser_error)
78 .context("parsing an already generated file")
79 })
80 } else {
81 Err(DarkluaError::uncached_work(source))
82 }
83 }
84}