1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
use crate::{SourceID, SourcePath, SourceText, Url};
use std::{borrow::Cow, collections::HashMap, path::Path};
mod display;

/// A [`Cache`] that fetches [`SourceText`]s from the filesystem.
#[derive(Default, Debug, Clone)]
pub struct SourceCache {
    files: HashMap<SourceID, SourceText>,
}

impl SourceCache {
    /// Create a new [`SourceCache`].
    pub fn load_local<P>(&mut self, path: P) -> Result<SourceID, std::io::Error>
    where
        P: AsRef<Path>,
    {
        let path = path.as_ref();
        let text = std::fs::read_to_string(&path)?;
        let source = SourceText::from(text).with_path(path);
        let name_hash = source.source_id();
        self.files.insert(name_hash, source);
        Ok(name_hash)
    }
    /// Create a new [`SourceCache`].
    pub fn load_remote(&mut self, url: Url) -> Result<SourceID, std::io::Error> {
        let path = url.as_ref();
        let text = std::fs::read_to_string(&path)?;
        let source = SourceText::from(text).with_remote(url);
        let name_hash = source.source_id();
        self.files.insert(name_hash, source);
        Ok(name_hash)
    }

    /// Create a new [`SourceCache`].
    pub fn load_text<T, N>(&mut self, text: T, name: N) -> SourceID
    where
        T: ToString,
        N: ToString,
    {
        let source = SourceText::snippet(text.to_string(), name.to_string());
        let name_hash = source.source_id();
        self.files.insert(name_hash, source);
        name_hash
    }
    /// Set the file identifier buy not update the context
    pub unsafe fn set_source<N>(&mut self, file: SourceID, source: N) -> bool
    where
        N: Into<Cow<'static, str>>,
    {
        match self.files.get_mut(&file) {
            Some(s) => {
                s.set_source(SourcePath::Snippet(source.into()));
                true
            }
            None => false,
        }
    }
    /// Create a new [`SourceCache`].
    pub fn fetch(&self, file: &SourceID) -> Result<&SourceText, std::io::Error> {
        match self.files.get(file) {
            Some(source) => Ok(source),
            None => Err(std::io::Error::new(std::io::ErrorKind::NotFound, format!("File {:?} not found", file))),
        }
    }
    /// Create a new [`SourceCache`].
    pub fn source_path(&self, file: &SourceID) -> Option<&SourcePath> {
        Some(&self.files.get(file)?.get_source())
    }
}