diff --git a/Makefile b/Makefile index d8c0c59..3c4f52e 100644 --- a/Makefile +++ b/Makefile @@ -104,7 +104,7 @@ build/bin/strcmp: src/strcmp.c build .PHONY: swab swab: build/bin/swab 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 \ -o $@ src/swab.rs diff --git a/src/swab.rs b/src/swab.rs index 26104eb..f48842c 100644 --- a/src/swab.rs +++ b/src/swab.rs @@ -5,23 +5,48 @@ use std::{ 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 { eprintln!("{}: {}", s, e); 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 { let argv = args().collect::>(); let mut buf: Vec = Vec::new(); let mut input = stdin(); let mut output = stdout().lock(); - let wordsize: usize = 2; - let force = false; + let mut opts = Parser::new(&argv, "fw:"); + 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::() { + Ok(w) if w % 2 == 0 => { wordsize = w; () }, + _ => { return usage(&argv[0]); }, + } + }, + _ => { return usage(&argv[0]); } + } + } + } buf.resize(wordsize, 0);