getopt.rs(3): optind support

This commit is contained in:
Emma Tebibyte 2024-06-04 14:28:19 -06:00
parent 78eacd660a
commit a5a9c91cb6
Signed by untrusted user: emma
GPG Key ID: 06FA419A1698C270

View File

@ -18,6 +18,21 @@
use std::ffi::{ c_int, c_char, CString, CStr }; use std::ffi::{ c_int, c_char, CString, CStr };
/* binding to getopt(3p) */
extern "C" {
static mut optarg: *mut c_char;
static mut _opterr: c_int;
static mut optind: c_int;
static mut optopt: c_int;
fn getopt(
___argc: c_int,
___argv: *const *mut c_char,
__shortopts: *const c_char,
) -> c_int;
}
pub struct Opt { pub struct Opt {
pub arg: Option<String>, pub arg: Option<String>,
pub ind: i32, pub ind: i32,
@ -50,7 +65,7 @@ impl GetOpt for Vec<String> {
let opts = CString::new(optstring).unwrap().into_raw(); let opts = CString::new(optstring).unwrap().into_raw();
let len = self.len() as c_int; let len = self.len() as c_int;
unsafe { // TODO: enable optind modification unsafe {
match getopt(len, argv_ptr, opts) { match getopt(len, argv_ptr, opts) {
/* From getopt(3p): /* From getopt(3p):
* *
@ -103,16 +118,24 @@ impl GetOpt for Vec<String> {
} }
} }
} }
/* binding to getopt(3p) */
extern "C" {
static mut optarg: *mut c_char;
static mut _opterr: c_int;
static mut optind: c_int;
static mut optopt: c_int;
fn getopt( /* From getopt(3p):
___argc: c_int, *
___argv: *const *mut c_char, * The variable optind is the index of the next element of the argv[]
__shortopts: *const c_char, * vector to be processed. It shall be initialized to 1 by the system, and
) -> c_int; * getopt() shall update it when it finishes with each element of argv[].
} * If the application sets optind to zero before calling getopt(), the
* behavior is unspecified. When an element of argv[] contains multiple
* option characters, it is unspecified how getopt() determines which
* options have already been processed.
*
* This API can be utilized using unsafe blocks and dereferencing:
*
* use getopt::OPTIND;
*
* unsafe { while *OPTIND < 5 {
* println!("{}", *OPTIND); // 1..4
* *OPTIND += 1;
* }}
*/
pub static mut OPTIND: *mut i32 = unsafe { std::ptr::addr_of_mut!(optind) };