egui/load/
bytes_loader.rs

1use super::*;
2
3/// Maps URI:s to [`Bytes`], e.g. found with `include_bytes!`.
4///
5/// By convention, the URI:s should be prefixed with `bytes://`.
6#[derive(Default)]
7pub struct DefaultBytesLoader {
8    cache: Mutex<HashMap<Cow<'static, str>, Bytes>>,
9}
10
11impl DefaultBytesLoader {
12    pub fn insert(&self, uri: impl Into<Cow<'static, str>>, bytes: impl Into<Bytes>) {
13        self.cache
14            .lock()
15            .entry(uri.into())
16            .or_insert_with_key(|_uri| {
17                let bytes: Bytes = bytes.into();
18
19                #[cfg(feature = "log")]
20                log::trace!("loaded {} bytes for uri {_uri:?}", bytes.len());
21
22                bytes
23            });
24    }
25}
26
27impl BytesLoader for DefaultBytesLoader {
28    fn id(&self) -> &str {
29        generate_loader_id!(DefaultBytesLoader)
30    }
31
32    fn load(&self, _: &Context, uri: &str) -> BytesLoadResult {
33        // We accept uri:s that don't start with `bytes://` too… for now.
34        match self.cache.lock().get(uri).cloned() {
35            Some(bytes) => Ok(BytesPoll::Ready {
36                size: None,
37                bytes,
38                mime: None,
39            }),
40            None => {
41                if uri.starts_with("bytes://") {
42                    Err(LoadError::Loading(
43                        "Bytes not found. Did you forget to call Context::include_bytes?".into(),
44                    ))
45                } else {
46                    Err(LoadError::NotSupported)
47                }
48            }
49        }
50    }
51
52    fn forget(&self, uri: &str) {
53        #[cfg(feature = "log")]
54        log::trace!("forget {uri:?}");
55
56        self.cache.lock().remove(uri);
57    }
58
59    fn forget_all(&self) {
60        #[cfg(feature = "log")]
61        log::trace!("forget all");
62
63        self.cache.lock().clear();
64    }
65
66    fn byte_size(&self) -> usize {
67        self.cache.lock().values().map(|bytes| bytes.len()).sum()
68    }
69}