getopt.rs(3): returns last parsed option

This commit is contained in:
Emma Tebibyte 2024-04-13 17:11:04 -06:00
parent 8c255e61fc
commit d1b77d652b
Signed by: emma
GPG Key ID: 06FA419A1698C270
1 changed files with 18 additions and 9 deletions

View File

@ -21,12 +21,13 @@ use std::ffi::{ c_int, c_char, CString, CStr };
pub struct Opt {
pub arg: Option<String>,
pub ind: i32,
pub opt: i32,
/* opt is set to either the current option or the one that cause an error */
pub opt: String,
}
pub enum OptError {
MissingArg,
UnknownOpt,
MissingArg(String),
UnknownOpt(String),
}
/* function signature */
@ -51,7 +52,7 @@ impl GetOpt for Vec<String> {
let len = self.len() as c_int;
unsafe {
let a = match getopt(len, argv_ptr, opts) {
match getopt(len, argv_ptr, opts) {
/* From getopt(3p):
*
* The getopt() function shall return the next option character
@ -69,10 +70,10 @@ impl GetOpt for Vec<String> {
* Otherwise, getopt() shall return -1 when all command line
* options are parsed. */
58 => { /* numerical ASCII value for ':' */
return Some(Err(OptError::MissingArg));
Some(Err(OptError::MissingArg(optopt.to_string())))
},
63 => { /* numerical ASCII value for '?' */
return Some(Err(OptError::UnknownOpt))
Some(Err(OptError::UnknownOpt(optopt.to_string())))
},
/* From getopt(3p):
*
@ -88,10 +89,18 @@ impl GetOpt for Vec<String> {
*
* getopt() shall return -1 after incrementing optind. */
-1 => return None,
_ => CStr::from_ptr(optarg).to_string_lossy().into_owned(),
};
opt => {
let arg = CStr::from_ptr(optarg)
.to_string_lossy()
.into_owned();
Some(Ok(Opt { arg: Some(a), ind: optind, opt: optopt }))
Some(Ok(Opt {
arg: Some(arg),
ind: optind,
opt: opt.to_string(),
}))
},
}
}
}
}