Trait veloren_common_assets::Loader

pub trait Loader<T> {
    // Required method
    fn load(
        content: Cow<'_, [u8]>,
        ext: &str,
    ) -> Result<T, Box<dyn Error + Send + Sync>>;
}
Expand description

Specifies how an asset is loaded.

With this trait, you can easily specify how you want your data to be loaded. This trait is generic, so the same Loader type can be used to load several asset types.

§Basic usage

Most of the time, you don’t need to implement this trait yourself, or even care about the definition, as there are implementations for common formats and conversions. Don’t forget to enable the corresponding feature if needed !

§Example

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

// The struct you want to load
#[derive(Deserialize)]
struct Point {
    x: i32,
    y: i32,
}

impl Asset for Point {
    const EXTENSION: &'static str = "ron";

    // Specify here how to convert raw data
    type Loader = loader::RonLoader;
}

§Implementing Loader

Function load does the conversion from raw bytes to the concrete Rust value.

§Example

use assets_manager::{Asset, BoxedError, loader::Loader};
use std::{borrow::Cow, error::Error, io, str};

enum Fruit {
    Apple,
    Banana,
    Pear,
}

struct FruitLoader;
impl Loader<Fruit> for FruitLoader {
    fn load(content: Cow<[u8]>, _: &str) -> Result<Fruit, BoxedError> {
        match str::from_utf8(&content)?.trim() {
            "apple" => Ok(Fruit::Apple),
            "banana" => Ok(Fruit::Banana),
            "pear" => Ok(Fruit::Pear),
            _ => Err("Invalid fruit".into()),
        }
    }
}

impl Asset for Fruit {
    const EXTENSION: &'static str = "txt";
    type Loader = FruitLoader;
}

Required Methods§

fn load( content: Cow<'_, [u8]>, ext: &str, ) -> Result<T, Box<dyn Error + Send + Sync>>

Loads an asset from its raw bytes representation.

The extension used to load the asset is also passed as parameter, which can be useful to guess the format if an asset type uses several extensions.

Object Safety§

This trait is not object safe.

Implementors§

§

impl Loader<Box<str>> for StringLoader

§

impl Loader<Box<[u8]>> for BytesLoader

§

impl Loader<String> for StringLoader

§

impl Loader<Vec<u8>> for BytesLoader

source§

impl Loader<DotVoxAsset> for DotVoxLoader

source§

impl Loader<Image> for ImageLoader

source§

impl Loader<ObjAsset> for ObjAssetLoader

§

impl Loader<SharedString> for StringLoader

§

impl Loader<FontArc> for FontLoader

§

impl Loader<FontVec> for FontLoader

§

impl Loader<SharedBytes> for BytesLoader

§

impl<T> Loader<T> for ParseLoader
where T: FromStr, Box<dyn Error + Send + Sync>: From<<T as FromStr>::Err>,

§

impl<T> Loader<T> for BincodeLoader
where T: for<'de> Deserialize<'de>,

§

impl<T> Loader<T> for JsonLoader
where T: for<'de> Deserialize<'de>,

§

impl<T> Loader<T> for RonLoader
where T: for<'de> Deserialize<'de>,

§

impl<T, U, L> Loader<T> for LoadFrom<U, L>
where U: Into<T>, L: Loader<U>,