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