Skip to main content

27_future_protocol/
27_future_protocol.rs

1use anput::bundle::DynamicBundle;
2use keket::{
3    database::{AssetDatabase, handle::AssetHandle, path::AssetPathStatic},
4    fetch::file::FileAssetFetch,
5    protocol::future::{FutureAssetProtocol, FutureStorageAccess},
6};
7use moirai::coroutine::yield_now;
8use std::error::Error;
9
10fn main() -> Result<(), Box<dyn Error>> {
11    /* ANCHOR: main */
12    let mut database = AssetDatabase::default()
13        .with_protocol(FutureAssetProtocol::new("lines").process(process_lines))
14        .with_fetch(FileAssetFetch::default().with_root("resources"));
15
16    let lines = database.schedule("lines://lorem.txt")?;
17
18    while database.is_busy() {
19        database.maintain()?;
20    }
21
22    println!(
23        "Lines count: {}",
24        lines.access::<&Vec<String>>(&database).len()
25    );
26    /* ANCHOR_END: main */
27
28    Ok(())
29}
30
31/* ANCHOR: async_asset_protocol */
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}
51/* ANCHOR_END: async_asset_protocol */