getopt.rs(3): makes optind part of the Opt struct

This commit is contained in:
Emma Tebibyte 2024-06-04 19:15:22 -06:00
parent b7283d54fe
commit 35ddc729fd
Signed by untrusted user: emma
GPG Key ID: 06FA419A1698C270

View File

@ -32,30 +32,9 @@ extern "C" {
) -> c_int; ) -> 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 struct Opt {
pub arg: Option<String>, pub arg: Option<String>,
pub ind: i32, pub ind: *mut i32,
pub opt: String, pub opt: String,
} }
@ -89,7 +68,7 @@ impl GetOpt for Vec<String> {
match getopt(len, argv_ptr, opts) { match getopt(len, argv_ptr, opts) {
/* From getopt(3p): /* 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. * specified on the command line.
* *
* A <colon> (':') shall be returned if getopt() detects a * A <colon> (':') shall be returned if getopt() detects a
@ -130,7 +109,22 @@ impl GetOpt for Vec<String> {
Some(Ok(Opt { Some(Ok(Opt {
arg: Some(arg), /* opt argument */ 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 */ opt: opt.to_string(), /* option itself */
})) }))
}, },