tinymist_vfs/
system.rs

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
70
71
72
73
74
use std::{fs::File, io::Read, path::Path};

use tinymist_std::ReadAllOnce;
use typst::diag::{FileError, FileResult};

use crate::{Bytes, PathAccessModel};

/// Provides SystemAccessModel that makes access to the local file system for
/// system compilation.
#[derive(Debug, Clone, Copy)]
pub struct SystemAccessModel;

impl SystemAccessModel {
    fn stat(&self, src: &Path) -> std::io::Result<SystemFileMeta> {
        let meta = std::fs::metadata(src)?;
        Ok(SystemFileMeta {
            is_dir: meta.is_dir(),
        })
    }
}

impl PathAccessModel for SystemAccessModel {
    fn content(&self, src: &Path) -> FileResult<Bytes> {
        let f = |e| FileError::from_io(e, src);
        let mut buf = Vec::<u8>::new();

        let meta = self.stat(src).map_err(f)?;

        if meta.is_dir {
            return Err(FileError::IsDirectory);
        }

        std::fs::File::open(src)
            .map_err(f)?
            .read_to_end(&mut buf)
            .map_err(f)?;
        Ok(Bytes::new(buf))
    }
}

/// Lazily opened file entry corresponding to a file in the local file system.
///
/// This is used by font loading instead of the [`SystemAccessModel`].
#[derive(Debug)]
pub struct LazyFile {
    path: std::path::PathBuf,
    file: Option<std::io::Result<File>>,
}

impl LazyFile {
    /// Create a new [`LazyFile`] with the given path.
    pub fn new(path: std::path::PathBuf) -> Self {
        Self { path, file: None }
    }
}

impl ReadAllOnce for LazyFile {
    fn read_all(mut self, buf: &mut Vec<u8>) -> std::io::Result<usize> {
        let file = self.file.get_or_insert_with(|| File::open(&self.path));
        let Ok(ref mut file) = file else {
            let err = file.as_ref().unwrap_err();
            // todo: clone error or hide error
            return Err(std::io::Error::new(err.kind(), err.to_string()));
        };

        file.read_to_end(buf)
    }
}

/// Meta data of a file in the local file system.
#[derive(Debug, Clone, Copy)]
pub struct SystemFileMeta {
    is_dir: bool,
}