swab(1): add argument parsing

This commit is contained in:
dtb 2024-02-24 03:04:05 -07:00
parent 3f0d95fe8f
commit e788947fc4
Signed by: trinity
GPG Key ID: 31FF85CCB6DC7641
2 changed files with 30 additions and 5 deletions

View File

@ -104,7 +104,7 @@ build/bin/strcmp: src/strcmp.c build
.PHONY: swab .PHONY: swab
swab: build/bin/swab swab: build/bin/swab
build/bin/swab: src/swab.rs build build/o/libsysexits.rlib build/bin/swab: src/swab.rs build build/o/libsysexits.rlib
$(RUSTC) $(RUSTFLAGS) \ $(RUSTC) $(RUSTFLAGS) --extern getopt=build/o/libgetopt.rlib \
--extern sysexits=build/o/libsysexits.rlib \ --extern sysexits=build/o/libsysexits.rlib \
-o $@ src/swab.rs -o $@ src/swab.rs

View File

@ -5,23 +5,48 @@ use std::{
vec::Vec vec::Vec
}; };
extern crate sysexits; extern crate getopt;
use getopt::{ Opt, Parser };
use sysexits::{ EX_OK, EX_OSERR }; extern crate sysexits;
use sysexits::{ EX_OK, EX_OSERR, EX_USAGE };
fn oserr(s: &str, e: Error) -> ExitCode { fn oserr(s: &str, e: Error) -> ExitCode {
eprintln!("{}: {}", s, e); eprintln!("{}: {}", s, e);
ExitCode::from(EX_OSERR as u8) ExitCode::from(EX_OSERR as u8)
} }
fn usage(s: &str) -> ExitCode {
eprintln!("Usage: {} (-f) (-w [wordsize])", s);
ExitCode::from(EX_USAGE as u8)
}
fn main() -> ExitCode { fn main() -> ExitCode {
let argv = args().collect::<Vec<String>>(); let argv = args().collect::<Vec<String>>();
let mut buf: Vec<u8> = Vec::new(); let mut buf: Vec<u8> = Vec::new();
let mut input = stdin(); let mut input = stdin();
let mut output = stdout().lock(); let mut output = stdout().lock();
let wordsize: usize = 2; let mut opts = Parser::new(&argv, "fw:");
let force = false; let mut force = false;
let mut wordsize: usize = 2;
loop {
match opts.next() {
None => break,
Some(opt) =>
match opt {
Ok(Opt('f', None)) => force = true,
Ok(Opt('w', Some(arg))) => {
match arg.parse::<usize>() {
Ok(w) if w % 2 == 0 => { wordsize = w; () },
_ => { return usage(&argv[0]); },
}
},
_ => { return usage(&argv[0]); }
}
}
}
buf.resize(wordsize, 0); buf.resize(wordsize, 0);