|
1 | 1 | use std::{
|
2 |
| - fs::{self, File}, |
3 |
| - io::Read, |
| 2 | + fs::{self, File, OpenOptions}, |
| 3 | + io::{Read, Seek, SeekFrom, Write}, |
4 | 4 | path::PathBuf,
|
5 | 5 | };
|
6 | 6 |
|
@@ -342,11 +342,35 @@ fn save_image(args: SaveImageArgs, config: &Config) -> Result<()> {
|
342 | 342 | Ok(())
|
343 | 343 | }
|
344 | 344 |
|
| 345 | +fn pad_to(file: &mut File, alignment: u64, pad_character: u8) -> Result<()> { |
| 346 | + let current_size = file.metadata().into_diagnostic()?.len(); |
| 347 | + let pad_mod = current_size % alignment; |
| 348 | + |
| 349 | + if pad_mod != 0 { |
| 350 | + let pad_size = alignment - pad_mod; |
| 351 | + |
| 352 | + // Move the file cursor to the end of the file |
| 353 | + file.seek(SeekFrom::End(0)).into_diagnostic()?; |
| 354 | + |
| 355 | + file.write_all(&vec![pad_character; pad_size as usize]) |
| 356 | + .into_diagnostic()?; |
| 357 | + } |
| 358 | + |
| 359 | + Ok(()) |
| 360 | +} |
| 361 | + |
345 | 362 | fn write_bin(args: WriteBinArgs, config: &Config) -> Result<()> {
|
346 | 363 | let mut flasher = connect(&args.connect_args, config, false, false)?;
|
347 | 364 | print_board_info(&mut flasher)?;
|
348 | 365 |
|
349 |
| - let mut f = File::open(&args.file).into_diagnostic()?; |
| 366 | + // if the file size is not divisible by 4, we need to pad FF bytes to the end of |
| 367 | + // the file, that's why we need `write` permission as well |
| 368 | + let mut f = OpenOptions::new() |
| 369 | + .read(true) |
| 370 | + .write(true) |
| 371 | + .open(&args.file) |
| 372 | + .into_diagnostic()?; |
| 373 | + pad_to(&mut f, 4, 0xFF)?; |
350 | 374 | let size = f.metadata().into_diagnostic()?.len();
|
351 | 375 | let mut buffer = Vec::with_capacity(size.try_into().into_diagnostic()?);
|
352 | 376 | f.read_to_end(&mut buffer).into_diagnostic()?;
|
|
0 commit comments