Skip to main content

AssetPath

Struct AssetPath 

Source
pub struct AssetPath<'a> { /* private fields */ }
Expand description

Represents an asset path, including its protocol, path, and optional metadata.

§Structure

The AssetPath is divided into three main components:

  • Protocol: The scheme of the asset path (e.g., file, http).
  • Path: The main path to the asset (e.g., /assets/texture.png).
  • Meta: Optional metadata for the asset, typically a query string (e.g., ?version=1).

Implementations§

Source§

impl<'a> AssetPath<'a>

Source

pub fn new(content: impl Into<Cow<'a, str>>) -> Self

Creates a new AssetPath from the given content.

Source

pub fn from_parts(protocol: &str, path: &str, meta: &str) -> Self

Constructs an AssetPath from separate protocol, path, and metadata strings.

Examples found in repository?
examples/28_protocol_extract.rs (lines 63-67)
62    fn rewrite_path(&self, path: AssetPathStatic) -> Result<AssetPathStatic, Box<dyn Error>> {
63        Ok(AssetPathStatic::from_parts(
64            path.protocol(),
65            path.path(),
66            "",
67        ))
68    }
More examples
Hide additional examples
examples/15_localized_assets.rs (lines 22-31)
11fn main() -> Result<(), Box<dyn Error>> {
12    /* ANCHOR: main */
13    let language = Arc::new(RwLock::new("en"));
14    let language2 = language.clone();
15
16    let mut database = AssetDatabase::default()
17        .with_protocol(TextAssetProtocol)
18        .with_fetch(RewriteAssetFetch::new(
19            FileAssetFetch::default().with_root("resources"),
20            move |path| {
21                // Rewrite input path to localized one.
22                Ok(AssetPath::from_parts(
23                    path.protocol(),
24                    &format!(
25                        "{}.{}{}",
26                        path.path_without_extension(),
27                        *language2.read().unwrap(),
28                        path.path_dot_extension().unwrap_or_default()
29                    ),
30                    path.meta(),
31                ))
32            },
33        ));
34
35    // Gets `text://localized.en.txt`.
36    let asset = database.ensure("text://localized.txt")?;
37    println!("English: {}", asset.access::<&String>(&database));
38
39    // Change language.
40    *language.write().unwrap() = "de";
41    database.storage.clear();
42
43    // Gets `text://localized.de.txt`.
44    let asset = database.ensure("text://localized.txt")?;
45    println!("German: {}", asset.access::<&String>(&database));
46    /* ANCHOR_END: main */
47
48    Ok(())
49}
examples/14_assets_versioning.rs (lines 27-36)
11fn main() -> Result<(), Box<dyn Error>> {
12    let mut database = AssetDatabase::default()
13        .with_protocol(TextAssetProtocol)
14        // Rewrite asset fetch allows to rewrite input asset paths to some other
15        // before inner fetch tries to load it.
16        .with_fetch(RewriteAssetFetch::new(
17            FileAssetFetch::default().with_root("resources"),
18            |path| {
19                // Get version from requested asset meta items or use current version.
20                let version = path
21                    .meta_items()
22                    .find(|(key, _)| *key == "v")
23                    .map(|(_, value)| value)
24                    .unwrap_or(VERSION);
25                // Build new asset path that includes version.
26                // Example: `protocol://dir/asset.v1.ext`
27                Ok(AssetPath::from_parts(
28                    path.protocol(),
29                    &format!(
30                        "{}.v{}{}",
31                        path.path_without_extension(),
32                        version,
33                        path.path_dot_extension().unwrap_or_default()
34                    ),
35                    path.meta(),
36                ))
37            },
38        ));
39
40    // Gets `text://versioned.v1.txt`.
41    let v1 = database.ensure("text://versioned.txt?v=1")?;
42    println!("Version 1: {}", v1.access::<&String>(&database));
43
44    // Gets `text://versioned.v2.txt`.
45    let v2 = database.ensure("text://versioned.txt")?;
46    println!("Version 2: {}", v2.access::<&String>(&database));
47
48    Ok(())
49}
Source

pub fn into_static(self) -> AssetPathStatic

Converts the AssetPath into a static version, consuming the current instance.

Source

pub fn content(&self) -> &str

Retrieves the full content of the AssetPath.

Source

pub fn protocol(&self) -> &str

Returns the protocol part of the AssetPath.

Examples found in repository?
examples/28_protocol_extract.rs (line 64)
62    fn rewrite_path(&self, path: AssetPathStatic) -> Result<AssetPathStatic, Box<dyn Error>> {
63        Ok(AssetPathStatic::from_parts(
64            path.protocol(),
65            path.path(),
66            "",
67        ))
68    }
More examples
Hide additional examples
examples/15_localized_assets.rs (line 23)
11fn main() -> Result<(), Box<dyn Error>> {
12    /* ANCHOR: main */
13    let language = Arc::new(RwLock::new("en"));
14    let language2 = language.clone();
15
16    let mut database = AssetDatabase::default()
17        .with_protocol(TextAssetProtocol)
18        .with_fetch(RewriteAssetFetch::new(
19            FileAssetFetch::default().with_root("resources"),
20            move |path| {
21                // Rewrite input path to localized one.
22                Ok(AssetPath::from_parts(
23                    path.protocol(),
24                    &format!(
25                        "{}.{}{}",
26                        path.path_without_extension(),
27                        *language2.read().unwrap(),
28                        path.path_dot_extension().unwrap_or_default()
29                    ),
30                    path.meta(),
31                ))
32            },
33        ));
34
35    // Gets `text://localized.en.txt`.
36    let asset = database.ensure("text://localized.txt")?;
37    println!("English: {}", asset.access::<&String>(&database));
38
39    // Change language.
40    *language.write().unwrap() = "de";
41    database.storage.clear();
42
43    // Gets `text://localized.de.txt`.
44    let asset = database.ensure("text://localized.txt")?;
45    println!("German: {}", asset.access::<&String>(&database));
46    /* ANCHOR_END: main */
47
48    Ok(())
49}
examples/08_dlcs_asset_packs.rs (line 35)
13fn main() -> Result<(), Box<dyn Error>> {
14    let mut database = AssetDatabase::default()
15        .with_protocol(TextAssetProtocol)
16        .with_protocol(BytesAssetProtocol)
17        .with_fetch(
18            RouterAssetFetch::default()
19                .route(
20                    |_| true,
21                    ContainerAssetFetch::new(ZipContainerPartialFetch::new(ZipArchive::new(
22                        File::open("./resources/main.zip")?,
23                    )?)),
24                    0,
25                )
26                .route(
27                    |path| path.path().starts_with("dlc/"),
28                    RewriteAssetFetch::new(
29                        ContainerAssetFetch::new(ZipContainerPartialFetch::new(ZipArchive::new(
30                            File::open("./resources/dlc.zip")?,
31                        )?)),
32                        |path| {
33                            Ok(format!(
34                                "{}://{}",
35                                path.protocol(),
36                                path.path_with_meta().strip_prefix("dlc/").unwrap()
37                            )
38                            .into())
39                        },
40                    ),
41                    1,
42                ),
43        );
44
45    let lorem = database.ensure("text://lorem.txt")?;
46    println!("Lorem Ipsum: {}", lorem.access::<&String>(&database));
47
48    let trash = database.ensure("bytes://dlc/trash.bin")?;
49    println!("Bytes: {:?}", trash.access::<&Vec<u8>>(&database));
50
51    Ok(())
52}
examples/14_assets_versioning.rs (line 28)
11fn main() -> Result<(), Box<dyn Error>> {
12    let mut database = AssetDatabase::default()
13        .with_protocol(TextAssetProtocol)
14        // Rewrite asset fetch allows to rewrite input asset paths to some other
15        // before inner fetch tries to load it.
16        .with_fetch(RewriteAssetFetch::new(
17            FileAssetFetch::default().with_root("resources"),
18            |path| {
19                // Get version from requested asset meta items or use current version.
20                let version = path
21                    .meta_items()
22                    .find(|(key, _)| *key == "v")
23                    .map(|(_, value)| value)
24                    .unwrap_or(VERSION);
25                // Build new asset path that includes version.
26                // Example: `protocol://dir/asset.v1.ext`
27                Ok(AssetPath::from_parts(
28                    path.protocol(),
29                    &format!(
30                        "{}.v{}{}",
31                        path.path_without_extension(),
32                        version,
33                        path.path_dot_extension().unwrap_or_default()
34                    ),
35                    path.meta(),
36                ))
37            },
38        ));
39
40    // Gets `text://versioned.v1.txt`.
41    let v1 = database.ensure("text://versioned.txt?v=1")?;
42    println!("Version 1: {}", v1.access::<&String>(&database));
43
44    // Gets `text://versioned.v2.txt`.
45    let v2 = database.ensure("text://versioned.txt")?;
46    println!("Version 2: {}", v2.access::<&String>(&database));
47
48    Ok(())
49}
Source

pub fn path(&self) -> &str

Returns the path part of the AssetPath.

Examples found in repository?
examples/28_protocol_extract.rs (line 65)
62    fn rewrite_path(&self, path: AssetPathStatic) -> Result<AssetPathStatic, Box<dyn Error>> {
63        Ok(AssetPathStatic::from_parts(
64            path.protocol(),
65            path.path(),
66            "",
67        ))
68    }
More examples
Hide additional examples
examples/24_future_store.rs (line 45)
44async fn tokio_save_file(path: AssetPathStatic, bytes: Vec<u8>) -> Result<(), Box<dyn Error>> {
45    let file_path = PathBuf::from("resources").join(path.path());
46
47    tokio::fs::create_dir_all(file_path.parent().unwrap()).await?;
48    tokio::fs::write(&file_path, bytes).await?;
49
50    Ok(())
51}
examples/02_zip.rs (line 43)
40    fn load_bytes(&mut self, path: AssetPath) -> Result<Vec<u8>, Box<dyn Error>> {
41        let mut file = self
42            .archive
43            .by_name(path.path())
44            .map_err(|error| format!("Could not read zip file: `{}` - {}", path.path(), error))?;
45        let mut bytes = vec![];
46        file.read_to_end(&mut bytes)?;
47        Ok(bytes)
48    }
examples/25_tokio_axum.rs (line 57)
56async fn tokio_load_file_bundle(path: AssetPathStatic) -> Result<DynamicBundle, Box<dyn Error>> {
57    let file_path = PathBuf::from("resources").join(path.path());
58
59    let bytes = tokio::fs::read(&file_path).await?;
60
61    let mut bundle = DynamicBundle::default();
62    bundle
63        .add_component(AssetBytesAreReadyToProcess(bytes))
64        .map_err(|_| format!("Failed to add bytes to bundle for asset: {path}"))?;
65    Ok(bundle)
66}
examples/23_future_fetch.rs (line 37)
36async fn tokio_load_file_bundle(path: AssetPathStatic) -> Result<DynamicBundle, Box<dyn Error>> {
37    let file_path = PathBuf::from("resources").join(path.path());
38
39    let bytes = tokio::fs::read(&file_path).await?;
40
41    let mut bundle = DynamicBundle::default();
42    bundle
43        .add_component(AssetBytesAreReadyToProcess(bytes))
44        .map_err(|_| format!("Failed to add bytes to bundle for asset: {path}"))?;
45    Ok(bundle)
46}
examples/27_future_protocol.rs (line 40)
32async fn process_lines(
33    handle: AssetHandle,
34    access: FutureStorageAccess,
35    bytes: Vec<u8>,
36) -> Result<DynamicBundle, Box<dyn Error>> {
37    let access = access.access()?;
38    let path = access.read().unwrap();
39    let path = path.component::<true, AssetPathStatic>(handle.entity())?;
40    println!("Processing {} asset lines asynchronously...", path.path());
41    let content = String::from_utf8(bytes)?;
42    let mut items = Vec::default();
43    for line in content.lines() {
44        println!("Processing line: {}", line);
45        items.push(line.to_owned());
46        yield_now().await;
47    }
48    println!("Lines processing done");
49    Ok(DynamicBundle::new(items).ok().unwrap())
50}
Source

pub fn path_extension(&self) -> Option<&str>

Returns the path part extension of the AssetPath.

Source

pub fn path_dot_extension(&self) -> Option<&str>

Returns the path part extension with preceding dot of the AssetPath.

Examples found in repository?
examples/15_localized_assets.rs (line 28)
11fn main() -> Result<(), Box<dyn Error>> {
12    /* ANCHOR: main */
13    let language = Arc::new(RwLock::new("en"));
14    let language2 = language.clone();
15
16    let mut database = AssetDatabase::default()
17        .with_protocol(TextAssetProtocol)
18        .with_fetch(RewriteAssetFetch::new(
19            FileAssetFetch::default().with_root("resources"),
20            move |path| {
21                // Rewrite input path to localized one.
22                Ok(AssetPath::from_parts(
23                    path.protocol(),
24                    &format!(
25                        "{}.{}{}",
26                        path.path_without_extension(),
27                        *language2.read().unwrap(),
28                        path.path_dot_extension().unwrap_or_default()
29                    ),
30                    path.meta(),
31                ))
32            },
33        ));
34
35    // Gets `text://localized.en.txt`.
36    let asset = database.ensure("text://localized.txt")?;
37    println!("English: {}", asset.access::<&String>(&database));
38
39    // Change language.
40    *language.write().unwrap() = "de";
41    database.storage.clear();
42
43    // Gets `text://localized.de.txt`.
44    let asset = database.ensure("text://localized.txt")?;
45    println!("German: {}", asset.access::<&String>(&database));
46    /* ANCHOR_END: main */
47
48    Ok(())
49}
More examples
Hide additional examples
examples/14_assets_versioning.rs (line 33)
11fn main() -> Result<(), Box<dyn Error>> {
12    let mut database = AssetDatabase::default()
13        .with_protocol(TextAssetProtocol)
14        // Rewrite asset fetch allows to rewrite input asset paths to some other
15        // before inner fetch tries to load it.
16        .with_fetch(RewriteAssetFetch::new(
17            FileAssetFetch::default().with_root("resources"),
18            |path| {
19                // Get version from requested asset meta items or use current version.
20                let version = path
21                    .meta_items()
22                    .find(|(key, _)| *key == "v")
23                    .map(|(_, value)| value)
24                    .unwrap_or(VERSION);
25                // Build new asset path that includes version.
26                // Example: `protocol://dir/asset.v1.ext`
27                Ok(AssetPath::from_parts(
28                    path.protocol(),
29                    &format!(
30                        "{}.v{}{}",
31                        path.path_without_extension(),
32                        version,
33                        path.path_dot_extension().unwrap_or_default()
34                    ),
35                    path.meta(),
36                ))
37            },
38        ));
39
40    // Gets `text://versioned.v1.txt`.
41    let v1 = database.ensure("text://versioned.txt?v=1")?;
42    println!("Version 1: {}", v1.access::<&String>(&database));
43
44    // Gets `text://versioned.v2.txt`.
45    let v2 = database.ensure("text://versioned.txt")?;
46    println!("Version 2: {}", v2.access::<&String>(&database));
47
48    Ok(())
49}
Source

pub fn path_without_extension(&self) -> &str

Returns the path part without extension of the AssetPath.

Examples found in repository?
examples/15_localized_assets.rs (line 26)
11fn main() -> Result<(), Box<dyn Error>> {
12    /* ANCHOR: main */
13    let language = Arc::new(RwLock::new("en"));
14    let language2 = language.clone();
15
16    let mut database = AssetDatabase::default()
17        .with_protocol(TextAssetProtocol)
18        .with_fetch(RewriteAssetFetch::new(
19            FileAssetFetch::default().with_root("resources"),
20            move |path| {
21                // Rewrite input path to localized one.
22                Ok(AssetPath::from_parts(
23                    path.protocol(),
24                    &format!(
25                        "{}.{}{}",
26                        path.path_without_extension(),
27                        *language2.read().unwrap(),
28                        path.path_dot_extension().unwrap_or_default()
29                    ),
30                    path.meta(),
31                ))
32            },
33        ));
34
35    // Gets `text://localized.en.txt`.
36    let asset = database.ensure("text://localized.txt")?;
37    println!("English: {}", asset.access::<&String>(&database));
38
39    // Change language.
40    *language.write().unwrap() = "de";
41    database.storage.clear();
42
43    // Gets `text://localized.de.txt`.
44    let asset = database.ensure("text://localized.txt")?;
45    println!("German: {}", asset.access::<&String>(&database));
46    /* ANCHOR_END: main */
47
48    Ok(())
49}
More examples
Hide additional examples
examples/14_assets_versioning.rs (line 31)
11fn main() -> Result<(), Box<dyn Error>> {
12    let mut database = AssetDatabase::default()
13        .with_protocol(TextAssetProtocol)
14        // Rewrite asset fetch allows to rewrite input asset paths to some other
15        // before inner fetch tries to load it.
16        .with_fetch(RewriteAssetFetch::new(
17            FileAssetFetch::default().with_root("resources"),
18            |path| {
19                // Get version from requested asset meta items or use current version.
20                let version = path
21                    .meta_items()
22                    .find(|(key, _)| *key == "v")
23                    .map(|(_, value)| value)
24                    .unwrap_or(VERSION);
25                // Build new asset path that includes version.
26                // Example: `protocol://dir/asset.v1.ext`
27                Ok(AssetPath::from_parts(
28                    path.protocol(),
29                    &format!(
30                        "{}.v{}{}",
31                        path.path_without_extension(),
32                        version,
33                        path.path_dot_extension().unwrap_or_default()
34                    ),
35                    path.meta(),
36                ))
37            },
38        ));
39
40    // Gets `text://versioned.v1.txt`.
41    let v1 = database.ensure("text://versioned.txt?v=1")?;
42    println!("Version 1: {}", v1.access::<&String>(&database));
43
44    // Gets `text://versioned.v2.txt`.
45    let v2 = database.ensure("text://versioned.txt")?;
46    println!("Version 2: {}", v2.access::<&String>(&database));
47
48    Ok(())
49}
Source

pub fn path_parts(&self) -> impl Iterator<Item = &str>

Splits the path into its component parts.

Source

pub fn meta(&self) -> &str

Returns the metadata part of the AssetPath.

Examples found in repository?
examples/15_localized_assets.rs (line 30)
11fn main() -> Result<(), Box<dyn Error>> {
12    /* ANCHOR: main */
13    let language = Arc::new(RwLock::new("en"));
14    let language2 = language.clone();
15
16    let mut database = AssetDatabase::default()
17        .with_protocol(TextAssetProtocol)
18        .with_fetch(RewriteAssetFetch::new(
19            FileAssetFetch::default().with_root("resources"),
20            move |path| {
21                // Rewrite input path to localized one.
22                Ok(AssetPath::from_parts(
23                    path.protocol(),
24                    &format!(
25                        "{}.{}{}",
26                        path.path_without_extension(),
27                        *language2.read().unwrap(),
28                        path.path_dot_extension().unwrap_or_default()
29                    ),
30                    path.meta(),
31                ))
32            },
33        ));
34
35    // Gets `text://localized.en.txt`.
36    let asset = database.ensure("text://localized.txt")?;
37    println!("English: {}", asset.access::<&String>(&database));
38
39    // Change language.
40    *language.write().unwrap() = "de";
41    database.storage.clear();
42
43    // Gets `text://localized.de.txt`.
44    let asset = database.ensure("text://localized.txt")?;
45    println!("German: {}", asset.access::<&String>(&database));
46    /* ANCHOR_END: main */
47
48    Ok(())
49}
More examples
Hide additional examples
examples/14_assets_versioning.rs (line 35)
11fn main() -> Result<(), Box<dyn Error>> {
12    let mut database = AssetDatabase::default()
13        .with_protocol(TextAssetProtocol)
14        // Rewrite asset fetch allows to rewrite input asset paths to some other
15        // before inner fetch tries to load it.
16        .with_fetch(RewriteAssetFetch::new(
17            FileAssetFetch::default().with_root("resources"),
18            |path| {
19                // Get version from requested asset meta items or use current version.
20                let version = path
21                    .meta_items()
22                    .find(|(key, _)| *key == "v")
23                    .map(|(_, value)| value)
24                    .unwrap_or(VERSION);
25                // Build new asset path that includes version.
26                // Example: `protocol://dir/asset.v1.ext`
27                Ok(AssetPath::from_parts(
28                    path.protocol(),
29                    &format!(
30                        "{}.v{}{}",
31                        path.path_without_extension(),
32                        version,
33                        path.path_dot_extension().unwrap_or_default()
34                    ),
35                    path.meta(),
36                ))
37            },
38        ));
39
40    // Gets `text://versioned.v1.txt`.
41    let v1 = database.ensure("text://versioned.txt?v=1")?;
42    println!("Version 1: {}", v1.access::<&String>(&database));
43
44    // Gets `text://versioned.v2.txt`.
45    let v2 = database.ensure("text://versioned.txt")?;
46    println!("Version 2: {}", v2.access::<&String>(&database));
47
48    Ok(())
49}
Source

pub fn meta_items(&self) -> impl Iterator<Item = (&str, &str)>

Parses the metadata into key-value pairs.

Examples found in repository?
examples/14_assets_versioning.rs (line 21)
11fn main() -> Result<(), Box<dyn Error>> {
12    let mut database = AssetDatabase::default()
13        .with_protocol(TextAssetProtocol)
14        // Rewrite asset fetch allows to rewrite input asset paths to some other
15        // before inner fetch tries to load it.
16        .with_fetch(RewriteAssetFetch::new(
17            FileAssetFetch::default().with_root("resources"),
18            |path| {
19                // Get version from requested asset meta items or use current version.
20                let version = path
21                    .meta_items()
22                    .find(|(key, _)| *key == "v")
23                    .map(|(_, value)| value)
24                    .unwrap_or(VERSION);
25                // Build new asset path that includes version.
26                // Example: `protocol://dir/asset.v1.ext`
27                Ok(AssetPath::from_parts(
28                    path.protocol(),
29                    &format!(
30                        "{}.v{}{}",
31                        path.path_without_extension(),
32                        version,
33                        path.path_dot_extension().unwrap_or_default()
34                    ),
35                    path.meta(),
36                ))
37            },
38        ));
39
40    // Gets `text://versioned.v1.txt`.
41    let v1 = database.ensure("text://versioned.txt?v=1")?;
42    println!("Version 1: {}", v1.access::<&String>(&database));
43
44    // Gets `text://versioned.v2.txt`.
45    let v2 = database.ensure("text://versioned.txt")?;
46    println!("Version 2: {}", v2.access::<&String>(&database));
47
48    Ok(())
49}
Source

pub fn has_meta_key(&self, key: &str) -> bool

Checks if path has specific meta key.

Examples found in repository?
examples/28_protocol_extract.rs (line 55)
53    fn extract_bundle_from_path(&self, path: &AssetPath) -> Result<DynamicBundle, Box<dyn Error>> {
54        let mut meta = Meta::default();
55        if path.has_meta_key("uppercase") {
56            meta.uppercase = true;
57        }
58        Ok(DynamicBundle::new(meta).unwrap())
59    }
Source

pub fn has_meta_key_value(&self, key: &str, value: &str) -> bool

Checks if path has specific meta key-value.

Examples found in repository?
examples/06_router_fetch.rs (line 19)
8fn main() -> Result<(), Box<dyn Error>> {
9    /* ANCHOR: main */
10    let mut database = AssetDatabase::default()
11        .with_protocol(TextAssetProtocol)
12        .with_protocol(BytesAssetProtocol)
13        .with_fetch(
14            // Router allows to combine multiple asset sources, so that proper one to use
15            // for given asset is selected by pattern in asset path.
16            RouterAssetFetch::default()
17                // Every asset that has `router=file` meta, will load asset from file.
18                .route(
19                    |path| path.has_meta_key_value("router", "file"),
20                    FileAssetFetch::default().with_root("resources"),
21                    0,
22                )
23                // Every asset that has `memory/` path prefix, will load from in-memory collection.
24                .route(
25                    |path| path.path().starts_with("memory/"),
26                    vec![(
27                        "memory/trash.bin".to_owned(),
28                        std::fs::read("./resources/trash.bin")?,
29                    )],
30                    1,
31                ),
32        );
33
34    // This asset will select file router.
35    let lorem = database.ensure("text://lorem.txt?router=file")?;
36    println!("Lorem Ipsum: {}", lorem.access::<&String>(&database));
37
38    // This asset will select memory router.
39    let trash = database.ensure("bytes://memory/trash.bin")?;
40    println!("Bytes: {:?}", trash.access::<&Vec<u8>>(&database));
41    /* ANCHOR_END: main */
42
43    Ok(())
44}
Source

pub fn try_meta(&self) -> Option<&str>

Tries to retrieve the metadata, returning None if it’s empty.

Source

pub fn path_with_meta(&self) -> &str

Returns the combined path and metadata of the AssetPath.

Examples found in repository?
examples/08_dlcs_asset_packs.rs (line 36)
13fn main() -> Result<(), Box<dyn Error>> {
14    let mut database = AssetDatabase::default()
15        .with_protocol(TextAssetProtocol)
16        .with_protocol(BytesAssetProtocol)
17        .with_fetch(
18            RouterAssetFetch::default()
19                .route(
20                    |_| true,
21                    ContainerAssetFetch::new(ZipContainerPartialFetch::new(ZipArchive::new(
22                        File::open("./resources/main.zip")?,
23                    )?)),
24                    0,
25                )
26                .route(
27                    |path| path.path().starts_with("dlc/"),
28                    RewriteAssetFetch::new(
29                        ContainerAssetFetch::new(ZipContainerPartialFetch::new(ZipArchive::new(
30                            File::open("./resources/dlc.zip")?,
31                        )?)),
32                        |path| {
33                            Ok(format!(
34                                "{}://{}",
35                                path.protocol(),
36                                path.path_with_meta().strip_prefix("dlc/").unwrap()
37                            )
38                            .into())
39                        },
40                    ),
41                    1,
42                ),
43        );
44
45    let lorem = database.ensure("text://lorem.txt")?;
46    println!("Lorem Ipsum: {}", lorem.access::<&String>(&database));
47
48    let trash = database.ensure("bytes://dlc/trash.bin")?;
49    println!("Bytes: {:?}", trash.access::<&Vec<u8>>(&database));
50
51    Ok(())
52}
Source

pub fn schedule( &self, database: &mut AssetDatabase, ) -> Result<AssetHandle, Box<dyn Error>>

Schedules the asset in the given AssetDatabase.

Source

pub fn ensure( &self, database: &mut AssetDatabase, ) -> Result<AssetHandle, Box<dyn Error>>

Ensures the asset is loaded in the given AssetDatabase.

Source

pub fn find(&self, database: &AssetDatabase) -> Option<AssetHandle>

Searches for the asset in the given AssetDatabase.

Examples found in repository?
examples/12_custom_protocol_advanced.rs (line 53)
45    fn contents(&self, database: &AssetDatabase) -> String {
46        let mut result = String::new();
47        let mut current = Some(self);
48        while let Some(asset) = current {
49            result.push_str(asset.content.as_str());
50            current = current
51                .as_ref()
52                .and_then(|asset| asset.next.as_ref())
53                .and_then(|path| path.find(database))
54                .and_then(|handle| handle.access_checked::<&Self>(database));
55            if current.is_some() {
56                result.push(' ');
57            }
58        }
59        result
60    }
More examples
Hide additional examples
examples/11_custom_protocol_simple.rs (line 53)
44    fn contents(&self, database: &AssetDatabase) -> String {
45        // Read this and it's siblings content to output.
46        let mut result = String::new();
47        let mut current = Some(self);
48        while let Some(asset) = current {
49            result.push_str(asset.content.as_str());
50            current = current
51                .as_ref()
52                .and_then(|asset| asset.next.as_ref())
53                .and_then(|path| path.find(database))
54                .and_then(|handle| handle.access_checked::<&Self>(database));
55            if current.is_some() {
56                result.push(' ');
57            }
58        }
59        result
60    }

Trait Implementations§

Source§

impl<'a> Clone for AssetPath<'a>

Source§

fn clone(&self) -> AssetPath<'a>

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
Source§

impl<'a> Debug for AssetPath<'a>

Source§

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

Formats the value using the given formatter. Read more
Source§

impl<'de, 'a> Deserialize<'de> for AssetPath<'a>

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for AssetPath<'_>

Source§

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

Formats the value using the given formatter. Read more
Source§

impl<'a> From<&'a str> for AssetPath<'a>

Source§

fn from(value: &'a str) -> Self

Converts to this type from the input type.
Source§

impl From<AssetPath<'_>> for String

Source§

fn from(val: AssetPath<'_>) -> Self

Converts to this type from the input type.
Source§

impl From<AssetPath<'static>> for AssetRef

Source§

fn from(path: AssetPathStatic) -> Self

Converts to this type from the input type.
Source§

impl<'a> From<Cow<'a, str>> for AssetPath<'a>

Source§

fn from(value: Cow<'a, str>) -> Self

Converts to this type from the input type.
Source§

impl From<String> for AssetPath<'_>

Source§

fn from(value: String) -> Self

Converts to this type from the input type.
Source§

impl Hash for AssetPath<'_>

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for AssetPath<'_>

Source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl<'a> PartialEq for AssetPath<'a>

Source§

fn eq(&self, other: &AssetPath<'a>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialOrd for AssetPath<'_>

Source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<'a> Serialize for AssetPath<'a>

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl<'a> Eq for AssetPath<'a>

Source§

impl<'a> StructuralPartialEq for AssetPath<'a>

Auto Trait Implementations§

§

impl<'a> Freeze for AssetPath<'a>

§

impl<'a> RefUnwindSafe for AssetPath<'a>

§

impl<'a> Send for AssetPath<'a>

§

impl<'a> Sync for AssetPath<'a>

§

impl<'a> Unpin for AssetPath<'a>

§

impl<'a> UnwindSafe for AssetPath<'a>

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<Q, K> Comparable<K> for Q
where Q: Ord + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn compare(&self, key: &K) -> Ordering

Compare self to key and return their ordering.
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> Finalize for T

Source§

unsafe fn finalize_raw(data: *mut ())

Safety Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

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

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

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> 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> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. 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.
Source§

impl<T> WithSubscriber for T

Source§

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
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

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

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

Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,