DEV Community

Cover image for Using Build.rs to inject build-time data to Web Assembly in Yew (OMR #2)
Jose
Jose

Posted on

Using Build.rs to inject build-time data to Web Assembly in Yew (OMR #2)

This is part 2 of an ongoing series, in which we build in public an Online Manga Reader (OMR) with unique features such as instant loading, thumbnail preview, rotation, dual page and cinema mode using Rust and Yew.

You can grab the repo here.

Read all of the posts here.

The Problem:

As I'm currently reading the chapters from the file system, I need a way to automatically count the available chapters and the number of pages each chapter has.

Unfortunately, you can't read from the filesystem in Yew.

Solution:

We need to generate a rust file that can be consumed.

We can achieve that using Rust's built-in build scripts.

Image description

Full Code below:

//<root>/build.rs (NOT <root>/src/build.rs)
use std::{collections::HashMap, fs};

/**
 * Recreates a HashMap<i16, i8> that from the directory structure of the manga
 * that is consumed by the state.rs
 */
fn main() {
    println!("cargo:rerun-if-changed=build.rs");
    let out_dir = "./src/";

    let mut chapter_state: HashMap<i16, i8> = HashMap::new();

    let dir_path = "./src/assets/manga/one_piece"; // replace with your directory path

    let manga_folders = fs::read_dir(dir_path).expect("Failed to read directory");

    for read in manga_folders {
        let entry = match read {
            Err(_) => continue,
            Ok(e) => e,
        };

        if !entry.path().is_dir() {
            continue;
        }

        if let Some(folder_name) = entry.path().file_name().and_then(|n| n.to_str()) {
            if let Ok(folder_num) = folder_name.parse::<i16>() {
                let count = fs::read_dir(entry.path())
                    .expect("Failed to read directory")
                    .count() as i8;

                chapter_state.insert(folder_num, count);
            }
        }
    }

    let mut sorted_manga_folders: Vec<(i16, i8)> = chapter_state.into_iter().collect();
    sorted_manga_folders.sort_by_key(|&(chapter, _)| -chapter);

    let mut chapter_concat: String = "[".to_owned();
    for (index, (chapter, page)) in sorted_manga_folders.iter().enumerate() {
        let comma_suffix = if index == sorted_manga_folders.len() - 1 {
            ""
        } else {
            ","
        };
        chapter_concat.push_str(&format!("({}, {}){}", chapter, page, comma_suffix));
    }

    chapter_concat.push_str("]");

    println!("cargo:warning={:?}", &chapter_concat);

    let chapter_map_rs = format!(
        "
        // Automatically generated - see build.rs
        // Do not modify manually!

        use std::collections::HashMap;
        pub fn get_chapters() -> HashMap<i16, i8> {{
        let chapter_state: HashMap<i16, i8> = HashMap::from({});
            chapter_state
        }}

    ",
        chapter_concat
    );

    let dest_path = format!("{}/chapter_map.rs", out_dir);
    fs::write(&dest_path, chapter_map_rs).unwrap();
}
Enter fullscreen mode Exit fullscreen mode
  1. We create a build.rs file in the root directory.

  2. We use a special println! macro that instructs rust to only run build.rs if the file has changed.

  3. The out_dir variable instructs Rust to send our file to the src folder so we can consume it later.

  4. We then iterate over the /src/assets/one_piece folder to create a HashMap with the number of the chapter as the key and the number of pages as the value.

  5. We then create a string that will serve as the content of the rust file. This is then generated to /src/chapter_map.rs with the following contents:


        // Automatically generated - see build.rs
        // Do not modify manually!

        use std::collections::HashMap;
        pub fn get_chapters() -> HashMap<i16, i8> {
        let chapter_state: HashMap<i16, i8> = HashMap::from([(1047, 20),(1046, 17),(1045, 20),(1044, 17),(1043, 17),(1042, 17)]);
            chapter_state
        }


Enter fullscreen mode Exit fullscreen mode

Note, that this content will depend on whether you have your assets placed inside.

  1. You then need to make the chapter_map.rs file available in main.rs file in order for you to import it on your file.

Follow me on other social media

I post regularly on:

LinkedIn - https://linkedin.com/in/javiasilis
Twitter - https://twitter.com/javiasilis
Enter fullscreen mode Exit fullscreen mode

Feel free to connect with me there!

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs