From 35ddc729fdc78334ab3656094ca0c6b81f32ca2d Mon Sep 17 00:00:00 2001 From: emma Date: Tue, 4 Jun 2024 19:15:22 -0600 Subject: [PATCH] getopt.rs(3): makes optind part of the Opt struct --- src/getopt.rs | 42 ++++++++++++++++++------------------------ 1 file changed, 18 insertions(+), 24 deletions(-) diff --git a/src/getopt.rs b/src/getopt.rs index 0324f87..62696e0 100644 --- a/src/getopt.rs +++ b/src/getopt.rs @@ -32,30 +32,9 @@ extern "C" { ) -> c_int; } -/* From getopt(3p): - * - * The variable optind is the index of the next element of the argv[] - * vector to be processed. It shall be initialized to 1 by the system, and - * 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) }; - pub struct Opt { pub arg: Option, - pub ind: i32, + pub ind: *mut i32, pub opt: String, } @@ -89,7 +68,7 @@ impl GetOpt for Vec { match getopt(len, argv_ptr, opts) { /* From getopt(3p): * - * The getopt() function shall return the next option character + * The getopt() f unction shall return the next option character * specified on the command line. * * A (':') shall be returned if getopt() detects a @@ -130,7 +109,22 @@ impl GetOpt for Vec { Some(Ok(Opt { arg: Some(arg), /* opt argument */ - ind: optind, /* opt index */ + /* From getopt(3p): + * + * The variable optind is the index of the next element + * of the argv[] vector to be processed. It shall be + * initialized to 1 by the system, and 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 is unsafe and can be utilized by + * dereferencing the ind field before reading to and + * writing from the optind memory. */ + ind: std::ptr::addr_of_mut!(optind), opt: opt.to_string(), /* option itself */ })) },