1use anyhow::{Context, Result};
10use clap::{Parser, ValueEnum};
11use log::info;
12use std::{
13 mem::size_of,
14 path::{Path, PathBuf},
15};
16
17#[derive(Parser, Debug)]
18#[command(name = "pad", about = "Zero-pads graph files to a length that is a multiple of a word size.", long_about = None, next_line_help = true)]
19pub struct CliArgs {
20 pub file: PathBuf,
22 #[clap(value_enum)]
24 pub word_size: WordSize,
25}
26
27#[derive(ValueEnum, Clone, Debug, Default)]
28pub enum WordSize {
29 U16,
31 U32,
33 #[default]
35 U64,
36 U128,
38}
39
40pub fn main(args: CliArgs) -> Result<()> {
41 let word_size = match args.word_size {
42 WordSize::U16 => size_of::<u16>(),
43 WordSize::U32 => size_of::<u32>(),
44 WordSize::U64 => size_of::<u64>(),
45 WordSize::U128 => size_of::<u128>(),
46 };
47
48 pad(args.file, word_size)
49}
50
51pub fn pad(path: impl AsRef<Path>, block_size: usize) -> Result<()> {
52 let path = path.as_ref();
53 let file_len = path
54 .metadata()
55 .with_context(|| format!("Cannot extract metadata from file {}", path.display()))?
56 .len();
57
58 let padded_len = file_len.next_multiple_of(block_size as u64);
59
60 if file_len == padded_len {
61 info!(
62 "The length of file {} is already a multiple of {}",
63 path.display(),
64 block_size
65 );
66 return Ok(());
67 }
68
69 let file = std::fs::File::options()
70 .read(true)
71 .write(true)
72 .open(path)
73 .with_context(|| format!("Cannot open file {} to pad", path.display()))?;
74 file.set_len(padded_len)
75 .with_context(|| format!("Cannot pad file {}", path.display()))?;
76 info!(
77 "File {} successfully zero-padded to a length multiple of {}",
78 path.display(),
79 block_size
80 );
81
82 Ok(())
83}