tinymist_world/font/
loader.rs

1use tinymist_std::ReadAllOnce;
2use typst::text::Font;
3
4use crate::Bytes;
5
6/// A FontLoader helps load a font from somewhere.
7pub trait FontLoader {
8    /// Loads a font.
9    fn load(&mut self) -> Option<Font>;
10}
11
12/// Loads a font from a buffer.
13pub struct BufferFontLoader {
14    /// The buffer to load the font from.
15    pub buffer: Option<Bytes>,
16    /// The index in a font file.
17    pub index: u32,
18}
19
20impl FontLoader for BufferFontLoader {
21    fn load(&mut self) -> Option<Font> {
22        Font::new(self.buffer.take().unwrap(), self.index)
23    }
24}
25
26/// Loads a font from a reader.
27pub struct LazyBufferFontLoader<R> {
28    /// The reader to load the font from.
29    pub read: Option<R>,
30    /// The index in a font file.
31    pub index: u32,
32}
33
34impl<R: ReadAllOnce + Sized> LazyBufferFontLoader<R> {
35    /// Creates a new lazy buffer font loader.
36    pub fn new(read: R, index: u32) -> Self {
37        Self {
38            read: Some(read),
39            index,
40        }
41    }
42}
43
44impl<R: ReadAllOnce + Sized> FontLoader for LazyBufferFontLoader<R> {
45    fn load(&mut self) -> Option<Font> {
46        let mut buf = vec![];
47        self.read.take().unwrap().read_all(&mut buf).ok()?;
48        Font::new(Bytes::new(buf), self.index)
49    }
50}