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    fn load(&mut self) -> Option<Font>;
9}
10
11/// Loads font from a buffer.
12pub struct BufferFontLoader {
13    pub buffer: Option<Bytes>,
14    pub index: u32,
15}
16
17impl FontLoader for BufferFontLoader {
18    fn load(&mut self) -> Option<Font> {
19        Font::new(self.buffer.take().unwrap(), self.index)
20    }
21}
22
23/// Loads font from a reader.
24pub struct LazyBufferFontLoader<R> {
25    pub read: Option<R>,
26    pub index: u32,
27}
28
29impl<R: ReadAllOnce + Sized> LazyBufferFontLoader<R> {
30    pub fn new(read: R, index: u32) -> Self {
31        Self {
32            read: Some(read),
33            index,
34        }
35    }
36}
37
38impl<R: ReadAllOnce + Sized> FontLoader for LazyBufferFontLoader<R> {
39    fn load(&mut self) -> Option<Font> {
40        let mut buf = vec![];
41        self.read.take().unwrap().read_all(&mut buf).ok()?;
42        Font::new(Bytes::new(buf), self.index)
43    }
44}