2021-03-18 22:13:31 +03:00
|
|
|
use anyhow::{anyhow, Result};
|
2021-04-06 14:44:38 +03:00
|
|
|
use std::{borrow::Cow, cell::RefCell, collections::HashMap};
|
2021-03-18 22:13:31 +03:00
|
|
|
|
2021-08-03 00:55:27 +03:00
|
|
|
pub trait AssetSource: 'static + Send + Sync {
|
2021-03-18 22:13:31 +03:00
|
|
|
fn load(&self, path: &str) -> Result<Cow<[u8]>>;
|
2021-08-03 00:55:27 +03:00
|
|
|
fn list(&self, path: &str) -> Vec<Cow<'static, str>>;
|
2021-03-18 22:13:31 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
impl AssetSource for () {
|
|
|
|
fn load(&self, path: &str) -> Result<Cow<[u8]>> {
|
|
|
|
Err(anyhow!(
|
|
|
|
"get called on empty asset provider with \"{}\"",
|
|
|
|
path
|
|
|
|
))
|
|
|
|
}
|
2021-08-03 00:55:27 +03:00
|
|
|
|
|
|
|
fn list(&self, _: &str) -> Vec<Cow<'static, str>> {
|
|
|
|
vec![]
|
|
|
|
}
|
2021-03-18 22:13:31 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
pub struct AssetCache {
|
|
|
|
source: Box<dyn AssetSource>,
|
2021-04-06 14:44:38 +03:00
|
|
|
svgs: RefCell<HashMap<String, usvg::Tree>>,
|
2021-03-18 22:13:31 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
impl AssetCache {
|
|
|
|
pub fn new(source: impl AssetSource) -> Self {
|
|
|
|
Self {
|
|
|
|
source: Box::new(source),
|
2021-04-06 14:44:38 +03:00
|
|
|
svgs: RefCell::new(HashMap::new()),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn svg(&self, path: &str) -> Result<usvg::Tree> {
|
|
|
|
let mut svgs = self.svgs.borrow_mut();
|
|
|
|
if let Some(svg) = svgs.get(path) {
|
|
|
|
Ok(svg.clone())
|
|
|
|
} else {
|
|
|
|
let bytes = self.source.load(path)?;
|
|
|
|
let svg = usvg::Tree::from_data(&bytes, &usvg::Options::default())?;
|
|
|
|
svgs.insert(path.to_string(), svg.clone());
|
|
|
|
Ok(svg)
|
2021-03-18 22:13:31 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|