getopt.rs(3): safe api around optind reading and setting

This commit is contained in:
Emma Tebibyte 2024-06-05 11:54:55 -06:00
parent 05cde15105
commit e862b7fec6
Signed by untrusted user: emma
GPG Key ID: 06FA419A1698C270

View File

@ -34,10 +34,16 @@ extern "C" {
pub struct Opt { pub struct Opt {
pub arg: Option<String>, pub arg: Option<String>,
pub ind: *mut i32, ind: *mut i32,
pub opt: String, pub opt: String,
} }
impl Opt {
pub fn index(&self) -> usize { unsafe { *self.ind as usize } }
pub fn set_index(&self, ind: i32) { unsafe { *self.ind = ind; } }
}
pub enum OptError { pub enum OptError {
MissingArg(String), MissingArg(String),
UnknownOpt(String), UnknownOpt(String),
@ -82,12 +88,12 @@ impl GetOpt for Vec<String> {
* *
* Otherwise, getopt() shall return -1 when all command line * Otherwise, getopt() shall return -1 when all command line
* options are parsed. */ * options are parsed. */
58 => { /* numerical ASCII value for ':' */ 58 => { /* numerical ASCII value for ':' */
Some(Err(OptError::MissingArg(optopt.to_string()))) Some(Err(OptError::MissingArg(optopt.to_string())))
}, },
63 => { /* numerical ASCII value for '?' */ 63 => { /* numerical ASCII value for '?' */
Some(Err(OptError::UnknownOpt(optopt.to_string()))) Some(Err(OptError::UnknownOpt(optopt.to_string())))
}, },
/* From getopt(3p): /* From getopt(3p):
* *
* If, when getopt() is called: * If, when getopt() is called:
@ -121,9 +127,8 @@ impl GetOpt for Vec<String> {
* characters, it is unspecified how getopt() * characters, it is unspecified how getopt()
* determines which options have already been processed. * determines which options have already been processed.
* *
* This API is unsafe and can be utilized by * This API is can be utilized with the index() and
* dereferencing the ind field before reading to and * set_index() methods implemented for Opt. */
* writing from the optind memory. */
ind: std::ptr::addr_of_mut!(optind), ind: std::ptr::addr_of_mut!(optind),
opt: opt.to_string(), /* option itself */ opt: opt.to_string(), /* option itself */
})) }))