Skip to content

Commit

Permalink
added a callback clojure to flash and clone functions
Browse files Browse the repository at this point in the history
Signed-off-by: Girish Joshi <[email protected]>
  • Loading branch information
girish946 committed Feb 6, 2024
1 parent 47e0469 commit 440fd1e
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
19 changes: 15 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,16 @@ fn calculate_checksum<R: Read>(reader: &mut R, size: usize) -> std::io::Result<S
Ok(format!("{:x}", hasher.finalize()))
}

pub fn clone(
pub fn clone<F>(
device_path: String,
output_path: String,
block_size: usize,
silent: bool,
) -> Result<(), Box<dyn std::error::Error>> {
callback_fn: F,
) -> Result<(), Box<dyn std::error::Error>>
where
F: Fn(f64) -> (),
{
if !silent {
println!(
"device: {}, output: {}, block_size: {}",
Expand Down Expand Up @@ -84,17 +88,23 @@ pub fn clone(
total_bytes_read += bytes_read;
if !silent {
println!("Read and written {total_bytes_read} bytes");
// calculate percentage and call callback
callback_fn((total_bytes_read as f64 / 100.0) as f64);
}
}
Ok(())
}

pub fn flash(
pub fn flash<F>(
img_path: String,
device_path: String,
block_size: usize,
silent: bool,
) -> Result<(), Box<dyn std::error::Error>> {
callback_fn: F,
) -> Result<(), Box<dyn std::error::Error>>
where
F: Fn(f64) -> (),
{
let mut img_file = match File::open(&img_path) {
Ok(file) => file,
Err(e) => {
Expand Down Expand Up @@ -174,6 +184,7 @@ pub fn flash(
let percentage = (count * 100) / file_size as usize;
if !silent {
println!("written {count}/{file_size} : {percentage}%");
callback_fn(percentage as f64);
}
}

Expand Down
8 changes: 6 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ enum Commands {
},
}

fn callback_fn(percentage: f64) {
println!("{percentage}%");
}

#[tokio::main]
pub async fn main() {
let cli = Cli::parse();
Expand All @@ -68,7 +72,7 @@ pub async fn main() {
Some(silent) => silent,
None => false,
};
let _ = match clone(device, file, blk_size, silent) {
let _ = match clone(device, file, blk_size, silent, callback_fn) {
Ok(_) => println!("Success"),
Err(e) => println!("Error: {}", e),
};
Expand All @@ -91,7 +95,7 @@ pub async fn main() {
Some(silent) => silent,
None => false,
};
let _ = match flash(file, device, blk_size, silent) {
let _ = match flash(file, device, blk_size, silent, callback_fn) {
Ok(_) => println!("Success"),
Err(e) => println!("Error: {}", e),
};
Expand Down

0 comments on commit 440fd1e

Please sign in to comment.