Skip to main content

23_future_fetch/
23_future_fetch.rs

1use anput::bundle::DynamicBundle;
2use keket::{
3    database::{AssetDatabase, path::AssetPathStatic},
4    fetch::{AssetBytesAreReadyToProcess, future::FutureAssetFetch},
5    protocol::bytes::BytesAssetProtocol,
6};
7use std::{error::Error, path::PathBuf};
8
9#[tokio::main]
10async fn main() -> Result<(), Box<dyn Error>> {
11    /* ANCHOR: main */
12    let mut database = AssetDatabase::default()
13        .with_protocol(BytesAssetProtocol)
14        // Future asset fetch uses async function to handle providing
15        // asset bytes asynchronously with async/await.
16        .with_fetch(FutureAssetFetch::new(tokio_load_file_bundle));
17
18    let package = database.ensure("bytes://package.zip")?;
19
20    // Run maintain passes to load and process loaded bytes.
21    while !package.is_ready_to_use(&database) {
22        database.maintain()?;
23        tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
24    }
25
26    println!(
27        "Package byte size: {}",
28        package.access::<&Vec<u8>>(&database).len()
29    );
30    /* ANCHOR_END: main */
31
32    Ok(())
33}
34
35/* ANCHOR: async_read_file */
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}
47/* ANCHOR_END: async_read_file */