Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 6383

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 27, 20242024-11-27T06:01:07+00:00 2024-11-27T06:01:07+00:00

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

  • 60k

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!

rustwebassemblywebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 1k
  • Popular
  • Answers
  • Author

    How to ensure that all the routes on my Symfony ...

    • 0 Answers
  • Author

    Insights into Forms in Flask

    • 0 Answers
  • Author

    Kick Start Your Next Project With Holo Theme

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.