egui/load/
bytes_loader.rs1use super::{
2 Bytes, BytesLoadResult, BytesLoader, BytesPoll, Context, Cow, HashMap, LoadError, Mutex,
3 generate_loader_id,
4};
5
6#[derive(Default)]
10pub struct DefaultBytesLoader {
11 cache: Mutex<HashMap<Cow<'static, str>, Bytes>>,
12}
13
14impl DefaultBytesLoader {
15 pub fn insert(&self, uri: impl Into<Cow<'static, str>>, bytes: impl Into<Bytes>) {
16 self.cache
17 .lock()
18 .entry(uri.into())
19 .or_insert_with_key(|_uri| {
20 let bytes: Bytes = bytes.into();
21
22 log::trace!("loaded {} bytes for uri {_uri:?}", bytes.len());
23
24 bytes
25 });
26 }
27}
28
29impl BytesLoader for DefaultBytesLoader {
30 fn id(&self) -> &'static str {
31 generate_loader_id!(DefaultBytesLoader)
32 }
33
34 fn load(&self, _: &Context, uri: &str) -> BytesLoadResult {
35 match self.cache.lock().get(uri).cloned() {
37 Some(bytes) => Ok(BytesPoll::Ready {
38 size: None,
39 bytes,
40 mime: None,
41 }),
42 None => {
43 if uri.starts_with("bytes://") {
44 Err(LoadError::Loading(
45 "Bytes not found. Did you forget to call Context::include_bytes?".into(),
46 ))
47 } else {
48 Err(LoadError::NotSupported)
49 }
50 }
51 }
52 }
53
54 fn forget(&self, uri: &str) {
55 log::trace!("forget {uri:?}");
56
57 self.cache.lock().remove(uri);
58 }
59
60 fn forget_all(&self) {
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}