simplify cache handling

This commit is contained in:
Christof Petig 2024-01-25 23:53:07 +01:00
parent 77af5ef097
commit bab8c713fb
2 changed files with 49 additions and 24 deletions

View File

@ -2,7 +2,6 @@
//! Load assets (images or voxel data) from files //! Load assets (images or voxel data) from files
#[cfg(feature = "plugins")] #[cfg(feature = "plugins")]
use assets_manager::SharedBytes;
use dot_vox::DotVoxData; use dot_vox::DotVoxData;
use image::DynamicImage; use image::DynamicImage;
use lazy_static::lazy_static; use lazy_static::lazy_static;
@ -123,7 +122,7 @@ pub trait AssetExt: Sized + Send + Sync + 'static {
/// Extension to AssetExt to combine Ron files from filesystem and plugins /// Extension to AssetExt to combine Ron files from filesystem and plugins
pub trait AssetCombined: AssetExt { pub trait AssetCombined: AssetExt {
fn load_and_combine(specifier: &str) -> Result<AssetHandle<Self>, BoxedError>; fn load_and_combine(specifier: &str) -> Result<AssetHandle<Self>, Error>;
#[track_caller] #[track_caller]
fn load_expect_combined(specifier: &str) -> AssetHandle<Self> { fn load_expect_combined(specifier: &str) -> AssetHandle<Self> {
@ -142,7 +141,7 @@ pub trait CacheCombined<'a> {
fn load_and_combine<A: Compound + Concatenate>( fn load_and_combine<A: Compound + Concatenate>(
self, self,
id: &str, id: &str,
) -> Result<&'a assets_manager::Handle<A>, BoxedError>; ) -> Result<&'a assets_manager::Handle<A>, Error>;
} }
/// Loads directory and all files in it /// Loads directory and all files in it
@ -172,17 +171,14 @@ impl<'a> CacheCombined<'a> for AnyCache<'a> {
fn load_and_combine<A: Compound + Concatenate>( fn load_and_combine<A: Compound + Concatenate>(
self, self,
specifier: &str, specifier: &str,
) -> Result<&'a assets_manager::Handle<A>, BoxedError> { ) -> Result<&'a assets_manager::Handle<A>, Error> {
#[cfg(feature = "plugins")] #[cfg(feature = "plugins")]
{ {
self.get_cached(specifier).map_or_else( self.get_cached(specifier).map_or_else(
|| { || {
// only create this combined object if is not yet cached
let id_bytes = SharedBytes::from_slice(specifier.as_bytes());
// as it was created from UTF8 it needs to be valid UTF8
let id = SharedString::from_utf8(id_bytes).unwrap();
tracing::info!("combine {specifier}"); tracing::info!("combine {specifier}");
let data: Result<A, _> = ASSETS.combine(|cache: AnyCache| A::load(cache, &id)); let data: Result<A, _> =
ASSETS.combine(|cache: AnyCache| cache.load_owned::<A>(specifier));
data.map(|data| self.get_or_insert(specifier, data)) data.map(|data| self.get_or_insert(specifier, data))
}, },
Ok, Ok,
@ -190,13 +186,13 @@ impl<'a> CacheCombined<'a> for AnyCache<'a> {
} }
#[cfg(not(feature = "plugins"))] #[cfg(not(feature = "plugins"))]
{ {
Ok(self.load(specifier)?) self.load(specifier)
} }
} }
} }
impl<T: Compound + Concatenate> AssetCombined for T { impl<T: Compound + Concatenate> AssetCombined for T {
fn load_and_combine(specifier: &str) -> Result<AssetHandle<Self>, BoxedError> { fn load_and_combine(specifier: &str) -> Result<AssetHandle<Self>, Error> {
ASSETS.as_any_cache().load_and_combine(specifier) ASSETS.as_any_cache().load_and_combine(specifier)
} }
} }
@ -296,8 +292,9 @@ where
{ {
fn load(_cache: AnyCache, id: &SharedString) -> Result<Self, BoxedError> { fn load(_cache: AnyCache, id: &SharedString) -> Result<Self, BoxedError> {
ASSETS ASSETS
.combine(|cache: AnyCache| <Ron<T> as Compound>::load(cache, id).map(|r| r.0)) .combine(|cache: AnyCache| cache.load_owned::<Ron<T>>(id).map(|ron| ron.into_inner()))
.map(MultiRon) .map(MultiRon)
.map_err(Into::<BoxedError>::into)
} }
} }

View File

@ -4,9 +4,10 @@ use crate::Concatenate;
use super::{fs::FileSystem, ASSETS_PATH}; use super::{fs::FileSystem, ASSETS_PATH};
use assets_manager::{ use assets_manager::{
asset::DirLoadable,
hot_reloading::EventSender, hot_reloading::EventSender,
source::{FileContent, Source, Tar}, source::{FileContent, Source, Tar},
AnyCache, AssetCache, BoxedError, AnyCache, AssetCache, BoxedError, Compound, Storable,
}; };
struct PluginEntry { struct PluginEntry {
@ -134,15 +135,15 @@ impl CombinedCache {
/// Combine objects from filesystem and plugins /// Combine objects from filesystem and plugins
pub fn combine<T: Concatenate>( pub fn combine<T: Concatenate>(
&self, &self,
mut load_from: impl FnMut(AnyCache) -> Result<T, BoxedError>, mut load_from: impl FnMut(AnyCache) -> Result<T, assets_manager::Error>,
) -> Result<T, BoxedError> { ) -> Result<T, assets_manager::Error> {
let mut result = load_from(self.0.raw_source().fs.as_any_cache()); let mut result = load_from(self.0.raw_source().fs.as_any_cache());
// Report a severe error from the filesystem asset even if later overwritten by // Report a severe error from the filesystem asset even if later overwritten by
// an Ok value from a plugin // an Ok value from a plugin
if let Err(ref fs_error) = result { if let Err(ref fs_error) = result {
match fs_error match fs_error
.source() .reason()
.and_then(|error_source| error_source.downcast_ref::<std::io::Error>()) .downcast_ref::<std::io::Error>()
.map(|io_error| io_error.kind()) .map(|io_error| io_error.kind())
{ {
Some(std::io::ErrorKind::NotFound) => (), Some(std::io::ErrorKind::NotFound) => (),
@ -161,8 +162,8 @@ impl CombinedCache {
// Report any error other than NotFound // Report any error other than NotFound
Err(plugin_error) => { Err(plugin_error) => {
match plugin_error match plugin_error
.source() .reason()
.and_then(|error_source| error_source.downcast_ref::<std::io::Error>()) .downcast_ref::<std::io::Error>()
.map(|io_error| io_error.kind()) .map(|io_error| io_error.kind())
{ {
Some(std::io::ErrorKind::NotFound) => (), Some(std::io::ErrorKind::NotFound) => (),
@ -190,11 +191,38 @@ impl CombinedCache {
.push(PluginEntry { path, cache }); .push(PluginEntry { path, cache });
Ok(()) Ok(())
} }
}
// Delegate all cache operations directly to the contained cache object // Just forward these methods to the cache
impl std::ops::Deref for CombinedCache { #[inline]
type Target = AssetCache<CombinedSource>; pub fn enhance_hot_reloading(&'static self) { self.0.enhance_hot_reloading(); }
fn deref(&self) -> &Self::Target { &self.0 } #[inline]
pub fn load_rec_dir<A: DirLoadable>(
&self,
id: &str,
) -> Result<&assets_manager::Handle<assets_manager::RecursiveDirectory<A>>, assets_manager::Error>
{
self.0.load_rec_dir(id)
}
#[inline]
pub fn load<A: Compound>(
&self,
id: &str,
) -> Result<&assets_manager::Handle<A>, assets_manager::Error> {
self.0.load(id)
}
#[inline]
pub fn get_or_insert<A: Storable>(&self, id: &str, a: A) -> &assets_manager::Handle<A> {
self.0.get_or_insert(id, a)
}
#[inline]
pub fn load_owned<A: Compound>(&self, id: &str) -> Result<A, assets_manager::Error> {
self.0.load_owned(id)
}
#[inline]
pub fn as_any_cache(&self) -> AnyCache { self.0.as_any_cache() }
} }