1use anyhow::{anyhow, Result};
2use std::{borrow::Cow, cell::RefCell, collections::HashMap};
3
4pub trait AssetSource: 'static + Send + Sync {
5 fn load(&self, path: &str) -> Result<Cow<[u8]>>;
6 fn list(&self, path: &str) -> Vec<Cow<'static, str>>;
7}
8
9impl AssetSource for () {
10 fn load(&self, path: &str) -> Result<Cow<[u8]>> {
11 Err(anyhow!(
12 "get called on empty asset provider with \"{}\"",
13 path
14 ))
15 }
16
17 fn list(&self, _: &str) -> Vec<Cow<'static, str>> {
18 vec![]
19 }
20}
21
22pub struct AssetCache {
23 source: Box<dyn AssetSource>,
24 svgs: RefCell<HashMap<String, usvg::Tree>>,
25}
26
27impl AssetCache {
28 pub fn new(source: impl AssetSource) -> Self {
29 Self {
30 source: Box::new(source),
31 svgs: RefCell::new(HashMap::new()),
32 }
33 }
34
35 pub fn svg(&self, path: &str) -> Result<usvg::Tree> {
36 let mut svgs = self.svgs.borrow_mut();
37 if let Some(svg) = svgs.get(path) {
38 Ok(svg.clone())
39 } else {
40 let bytes = self.source.load(path)?;
41 let svg = usvg::Tree::from_data(&bytes, &usvg::Options::default())?;
42 svgs.insert(path.to_string(), svg.clone());
43 Ok(svg)
44 }
45 }
46}