From e862b7fec6a1fa12222ce298b4df8c9cdbee7d89 Mon Sep 17 00:00:00 2001 From: emma Date: Wed, 5 Jun 2024 11:54:55 -0600 Subject: [PATCH] getopt.rs(3): safe api around optind reading and setting --- src/getopt.rs | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/src/getopt.rs b/src/getopt.rs index 62696e0..dca53e0 100644 --- a/src/getopt.rs +++ b/src/getopt.rs @@ -34,10 +34,16 @@ extern "C" { pub struct Opt { pub arg: Option, - pub ind: *mut i32, + ind: *mut i32, 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 { MissingArg(String), UnknownOpt(String), @@ -82,12 +88,12 @@ impl GetOpt for Vec { * * Otherwise, getopt() shall return -1 when all command line * options are parsed. */ - 58 => { /* numerical ASCII value for ':' */ - Some(Err(OptError::MissingArg(optopt.to_string()))) - }, - 63 => { /* numerical ASCII value for '?' */ - Some(Err(OptError::UnknownOpt(optopt.to_string()))) - }, + 58 => { /* numerical ASCII value for ':' */ + Some(Err(OptError::MissingArg(optopt.to_string()))) + }, + 63 => { /* numerical ASCII value for '?' */ + Some(Err(OptError::UnknownOpt(optopt.to_string()))) + }, /* From getopt(3p): * * If, when getopt() is called: @@ -121,9 +127,8 @@ impl GetOpt for Vec { * characters, it is unspecified how getopt() * determines which options have already been processed. * - * This API is unsafe and can be utilized by - * dereferencing the ind field before reading to and - * writing from the optind memory. */ + * This API is can be utilized with the index() and + * set_index() methods implemented for Opt. */ ind: std::ptr::addr_of_mut!(optind), opt: opt.to_string(), /* option itself */ }))