AssetCache

Struct AssetCache 

pub struct AssetCache(Arc<AssetCacheInner>);
Expand description

The main structure of this crate, used to load and store assets.

It uses interior mutability, so assets can be added in the cache without requiring a mutable reference, but one is required to remove an asset.

Within the cache, assets are identified with their type and a string. This string is constructed from the asset path, replacing / by . and removing the extension. Given that, you cannot use . in your file names except for the extension.

§Example

use assets_manager::{Asset, AssetCache};
use serde::Deserialize;

#[derive(Debug, Deserialize, Asset)]
#[asset_format = "ron"]
struct Point {
    x: i32,
    y: i32,
}

// Create a cache
let cache = AssetCache::new("assets")?;

// Get an asset from the file `assets/common/position.ron`
let point_handle = cache.load::<Point>("common.position")?;

// Read it
let point = point_handle.read();
println!("Loaded position: {:?}", point);

// Release the lock
drop(point);

// Use hot-reloading
loop {
    println!("Position: {:?}", point_handle.read());
}

Tuple Fields§

§0: Arc<AssetCacheInner>

Implementations§

§

impl AssetCache

pub fn new<P>(path: P) -> Result<AssetCache, Error>
where P: AsRef<Path>,

Creates a cache that loads assets from the given directory.

§Errors

An error will be returned if path is not valid readable directory.

pub fn with_source<S>(source: S) -> AssetCache
where S: Source + Send + Sync + 'static,

Creates a cache that loads assets from the given source and tries to start hot-reloading (if feature hot-reloading is used).

If hot-reloading fails to start, an error is logged.

pub fn without_hot_reloading<S>(source: S) -> AssetCache
where S: Source + Send + Sync + 'static,

Creates a cache that loads assets from the given source.

pub fn make_child(&self) -> AssetCache

Makes a new cache with self as parent.

pub fn source(&self) -> impl Source + Send + Sync

Returns a reference to the cache’s Source.

pub fn downcast_raw_source<S>(&self) -> Option<&S>
where S: Source + 'static,

Returns a reference to the cache’s Source.

pub fn parent(&self) -> Option<&AssetCache>

Returns a reference to the cache’s parent, if any.

pub fn ancestors(&self) -> impl Iterator<Item = &AssetCache>

Returns an iterator over self and its ancestors.

let cache = assets_manager::AssetCache::new("assets")?;
let child = cache.make_child();
let grandchild = child.make_child();

let mut ancestors = grandchild.ancestors();

assert!(ancestors.next().is_some()); // `grandchild`
assert!(ancestors.next().is_some()); // `child`
assert!(ancestors.next().is_some()); // `cache`
assert!(ancestors.next().is_none());

pub fn no_record<T, F>(&self, f: F) -> T
where F: FnOnce() -> T,

Temporarily prevent Asset dependencies to be recorded.

This function disables dependencies recording in Asset::load. Assets loaded during the given closure will not be recorded as dependencies and the currently loading asset will not be reloaded when they are.

When hot-reloading is disabled or if the cache’s Source does not support hot-reloading, this function only returns the result of the closure given as parameter.

pub fn load<T>(&self, id: &str) -> Result<&Handle<T>, Error>
where T: Asset,

Loads an asset.

If the asset is not found in the cache, it is loaded from the source.

pub fn load_expect<T>(&self, id: &str) -> &Handle<T>
where T: Asset,

Loads an asset and panic if an error happens.

§Panics

Panics if an error happens while loading the asset.

pub fn get<T>(&self, id: &str) -> Option<&Handle<T>>
where T: Storable,

Gets a value from the cache.

This function does not attempt to load the value from the source if it is not found in the cache.

pub fn get_cached<T>(&self, id: &str) -> Option<&Handle<T>>
where T: Storable,

👎Deprecated: Use get instead

Deprecated name of get.

pub fn get_untyped( &self, id: &str, type_id: TypeId, ) -> Option<&Handle<dyn Any + Sync + Send>>

Gets a value with the given type from the cache.

This is an equivalent of get but with a dynamic type.

pub fn get_cached_untyped( &self, id: &str, type_id: TypeId, ) -> Option<&Handle<dyn Any + Sync + Send>>

👎Deprecated: Use get instead

Deprecated name of get_untyped.

pub fn get_or_insert<T>(&self, id: &str, default: T) -> &Handle<T>
where T: Storable,

Gets a value from the cache or inserts one.

Assets added via this function will never be reloaded.

pub fn contains<T>(&self, id: &str) -> bool
where T: Storable,

Returns true if the cache contains the specified asset.

pub fn load_dir<T>(&self, id: &str) -> Result<&Handle<Directory<T>>, Error>
where T: DirLoadable + Asset,

Loads a directory.

The directory’s id is constructed the same way as assets. To specify the cache’s root, give the empty string ("") as id.

Note that this function only gets the ids of assets, and that are not actually loaded. The returned handle can be use to iterate over them.

§Errors

An error is returned if the given id does not match a valid readable directory.

pub fn load_rec_dir<T>( &self, id: &str, ) -> Result<&Handle<RecursiveDirectory<T>>, Error>
where T: DirLoadable + Asset,

Loads a directory and its subdirectories.

The directory’s id is constructed the same way as assets. To specify the cache’s root, give the empty string ("") as id.

Note that this function only gets the ids of assets, and that are not actually loaded. The returned handle can be use to iterate over them.

§Errors

An error is returned if the given id does not match a valid readable directory.

When loading a directory recursively, directories that can’t be read are ignored.

pub fn load_owned<T>(&self, id: &str) -> Result<T, Error>
where T: Asset,

Loads an owned version of an asset.

Note that the asset will not be fetched from the cache nor will it be cached. In addition, hot-reloading does not affect the returned value.

This can be useful if you need ownership on a non-clonable value.

Inside an implementation Asset::load, you should use T::load directly.

pub fn is_hot_reloaded(&self) -> bool

Returns true if values stored in this cache may be hot-reloaded.

pub fn iter(&self) -> impl Iterator<Item = &Handle<dyn Any + Sync + Send>>

Iterate on all assets in this cache and its ancestors.

§Deadlocks

Using this function will cause deadlock if trying to insert asset in this cache or its ancestors in the current thread while the iterator is alive. You can work around that by collecting the iterator to a Vec first.

pub fn iter_by_type<T>(&self) -> impl Iterator<Item = &Handle<T>>
where T: Storable,

Iterate on all assets of a given type in this cache and its ancestors.

§Deadlocks

Using this function will cause deadlock if trying to insert asset in this cache or its ancestors in the current thread while the iterator is alive. You can work around that by collecting the iterator to a Vec first.

Trait Implementations§

Source§

impl CacheCombined for AssetCache

Source§

fn load_and_combine<A: Asset + Concatenate>( &self, specifier: &str, ) -> Result<&Handle<A>, Error>

§

impl Clone for AssetCache

§

fn clone(&self) -> AssetCache

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
§

impl Debug for AssetCache

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

impl<T> Storable for T
where T: Send + Sync + 'static,