Skip to main content

c/
getopt_impl.rs

1// Copyright (c) 2026 Meng Zhuo
2// SPDX-License-Identifier: BSD-3-Clause
3
4// getopt / getopt_long / getopt_long_only (port of musl's implementation).
5
6#[repr(C)]
7#[derive(Copy, Clone)]
8pub struct LongOption {
9    pub name: *const c_char,
10    pub has_arg: c_int,
11    pub flag: *mut c_int,
12    pub val: c_int,
13}
14
15#[no_mangle]
16pub static mut __optpos: c_int = 0;
17#[no_mangle]
18pub static mut __optreset: c_int = 0;
19
20unsafe fn getopt_reset_if_needed() {
21    if optind == 0 || __optreset != 0 || optreset != 0 {
22        __optreset = 0;
23        optreset = 0;
24        __optpos = 0;
25        optind = 1;
26    }
27}
28
29unsafe fn opt_char_len(s: *const c_char) -> usize {
30    // Option characters are bytes; UTF-8 continuation bytes are part of the
31    // same option character for the purposes of matching.
32    let b = *s as u8;
33    if b < 0x80 { 1 }
34    else if b >= 0xf0 { 4 }
35    else if b >= 0xe0 { 3 }
36    else if b >= 0xc0 { 2 }
37    else { 1 }
38}
39
40#[no_mangle]
41pub unsafe extern "C" fn getopt(
42    argc: c_int,
43    argv: *const *const c_char,
44    optstring_in: *const c_char,
45) -> c_int {
46    getopt_reset_if_needed();
47    if argc <= 0 || argv.is_null() || optstring_in.is_null() { return -1; }
48    if optind >= argc { return -1; }
49    let av = argv.add(optind as usize);
50    if (*av).is_null() { return -1; }
51    let arg = *av;
52    if *arg != b'-' as c_char {
53        if *optstring_in == b'-' as c_char {
54            optarg = arg as *mut c_char;
55            optind += 1;
56            return 1;
57        }
58        return -1;
59    }
60    if *arg.add(1) == 0 { return -1; }
61    if *arg.add(1) == b'-' as c_char && *arg.add(2) == 0 {
62        optind += 1;
63        return -1;
64    }
65    if __optpos == 0 { __optpos = 1; }
66    let clen = opt_char_len(arg.add(__optpos as usize));
67    let c = *arg.add(__optpos as usize) as u8;
68    let optchar = arg.add(__optpos as usize);
69    __optpos += clen as c_int;
70    if *arg.add(__optpos as usize) == 0 {
71        optind += 1;
72        __optpos = 0;
73    }
74
75    let mut spec = optstring_in;
76    if *spec == b'-' as c_char || *spec == b'+' as c_char { spec = spec.add(1); }
77
78    let mut i = 0usize;
79    let mut found = false;
80    while *spec.add(i) != 0 {
81        if *spec.add(i) as u8 == c { found = true; break; }
82        i += 1;
83    }
84    if !found || c == b':' {
85        optopt = c as c_int;
86        if *spec != b':' as c_char && opterr != 0 {
87            let prog = if !(*argv).is_null() { *argv } else { b"\0".as_ptr() as *const c_char };
88            crate::fprintf(
89                crate::stderr,
90                b"%s: unrecognized option: %.*s\n\0".as_ptr() as *const c_char,
91                prog,
92                clen as c_int,
93                optchar,
94            );
95        }
96        return b'?' as c_int;
97    }
98    if *spec.add(i + 1) == b':' as c_char {
99        optarg = core::ptr::null_mut();
100        if *spec.add(i + 2) != b':' as c_char || __optpos != 0 {
101            if optind >= argc {
102                optopt = c as c_int;
103                if *spec == b':' as c_char { return b':' as c_int; }
104                if opterr != 0 {
105                    let prog = if !(*argv).is_null() { *argv } else { b"\0".as_ptr() as *const c_char };
106                    crate::fprintf(
107                        crate::stderr,
108                        b"%s: option requires an argument: %.*s\n\0".as_ptr() as *const c_char,
109                        prog,
110                        clen as c_int,
111                        optchar,
112                    );
113                }
114                return b'?' as c_int;
115            }
116            optarg = *argv.add(optind as usize) as *mut c_char;
117            optind += 1;
118            if __optpos != 0 { optarg = optarg.add(__optpos as usize); }
119            __optpos = 0;
120        }
121    }
122    c as c_int
123}
124
125unsafe fn getopt_permute(argv: *mut *mut c_char, dest: isize, src: isize) {
126    let tmp = *argv.offset(src);
127    let mut i = src;
128    while i > dest {
129        *argv.offset(i) = *argv.offset(i - 1);
130        i -= 1;
131    }
132    *argv.offset(dest) = tmp;
133}
134
135unsafe fn getopt_long_core(
136    argc: c_int,
137    argv: *const *const c_char,
138    optstring: *const c_char,
139    longopts: *const LongOption,
140    idx: *mut c_int,
141    longonly: bool,
142) -> c_int {
143    if optstring.is_null() { return -1; }
144    optarg = core::ptr::null_mut();
145    let cur = *argv.add(optind as usize);
146    let is_long = !longopts.is_null()
147        && *cur == b'-' as c_char
148        && ((longonly && *cur.add(1) != 0 && *cur.add(1) != b'-' as c_char)
149            || (*cur.add(1) == b'-' as c_char && *cur.add(2) != 0));
150    if is_long {
151        let colon = *optstring.add(if *optstring == b'+' as c_char || *optstring == b'-' as c_char { 1 } else { 0 }) == b':' as c_char;
152        let start = cur.add(1);
153        let mut cnt = 0;
154        let mut match_idx = 0usize;
155        let mut arg: *const c_char = core::ptr::null();
156        let mut i = 0usize;
157        loop {
158            let opt = (*longopts.add(i)).name;
159            if opt.is_null() { break; }
160            let mut o = start;
161            if *o == b'-' as c_char { o = o.add(1); }
162            let mut n = opt;
163            while *o != 0 && *o != b'=' as c_char && *o == *n {
164                o = o.add(1);
165                n = n.add(1);
166            }
167            if *o != 0 && *o != b'=' as c_char {
168                i += 1;
169                continue;
170            }
171            arg = o;
172            match_idx = i;
173            if *n == 0 { cnt = 1; break; }
174            cnt += 1;
175            i += 1;
176        }
177        if cnt == 1 {
178            let opt = arg;
179            optind += 1;
180            let entry = *longopts.add(match_idx);
181            if *opt == b'=' as c_char {
182                if entry.has_arg == 0 {
183                    optopt = entry.val;
184                    if colon || opterr == 0 { return b'?' as c_int; }
185                    crate::fprintf(
186                        crate::stderr,
187                        b"%s: option does not take an argument: %s\n\0".as_ptr() as *const c_char,
188                        *argv,
189                        entry.name,
190                    );
191                    return b'?' as c_int;
192                }
193                optarg = opt.add(1) as *mut c_char;
194            } else if entry.has_arg == 1 {
195                if optind >= argc {
196                    optopt = entry.val;
197                    if colon { return b':' as c_int; }
198                    if opterr == 0 { return b'?' as c_int; }
199                    crate::fprintf(
200                        crate::stderr,
201                        b"%s: option requires an argument: %s\n\0".as_ptr() as *const c_char,
202                        *argv,
203                        entry.name,
204                    );
205                    return b'?' as c_int;
206                }
207                optarg = *argv.add(optind as usize) as *mut c_char;
208                optind += 1;
209            }
210            if !idx.is_null() { *idx = match_idx as c_int; }
211            if !entry.flag.is_null() {
212                *entry.flag = entry.val;
213                return 0;
214            }
215            return entry.val;
216        }
217        if *cur.add(1) == b'-' as c_char {
218            optopt = 0;
219            if !colon && opterr != 0 {
220                crate::fprintf(
221                    crate::stderr,
222                    if cnt != 0 {
223                        b"%s: option is ambiguous: %s\n\0".as_ptr() as *const c_char
224                    } else {
225                        b"%s: unrecognized option: %s\n\0".as_ptr() as *const c_char
226                    },
227                    *argv,
228                    cur.add(2),
229                );
230            }
231            optind += 1;
232            return b'?' as c_int;
233        }
234    }
235    getopt(argc, argv, optstring)
236}
237
238unsafe fn getopt_long_impl(
239    argc: c_int,
240    argv: *const *const c_char,
241    optstring: *const c_char,
242    longopts: *const LongOption,
243    idx: *mut c_int,
244    longonly: bool,
245) -> c_int {
246    getopt_reset_if_needed();
247    if argc <= 0 || argv.is_null() || optstring.is_null() { return -1; }
248    if optind >= argc || (*argv.add(optind as usize)).is_null() { return -1; }
249    let skipped = optind;
250    if *optstring != b'+' as c_char && *optstring != b'-' as c_char {
251        let mut i = optind;
252        loop {
253            if i >= argc || (*argv.add(i as usize)).is_null() { return -1; }
254            let a = *argv.add(i as usize);
255            if *a == b'-' as c_char && *a.add(1) != 0 { break; }
256            i += 1;
257        }
258        optind = i;
259    }
260    let resumed = optind;
261    let ret = getopt_long_core(argc, argv, optstring, longopts, idx, longonly);
262    if resumed > skipped {
263        let cnt = optind - resumed;
264        let mut i = 0;
265        while i < cnt {
266            getopt_permute(argv as *mut *mut c_char, skipped as isize, (optind - 1) as isize);
267            i += 1;
268        }
269        optind = skipped + cnt;
270    }
271    ret
272}
273
274#[no_mangle]
275pub unsafe extern "C" fn getopt_long(
276    argc: c_int,
277    argv: *const *const c_char,
278    optstring: *const c_char,
279    longopts: *const LongOption,
280    idx: *mut c_int,
281) -> c_int {
282    getopt_long_impl(argc, argv, optstring, longopts, idx, false)
283}
284
285#[no_mangle]
286pub unsafe extern "C" fn getopt_long_only(
287    argc: c_int,
288    argv: *const *const c_char,
289    optstring: *const c_char,
290    longopts: *const LongOption,
291    idx: *mut c_int,
292) -> c_int {
293    getopt_long_impl(argc, argv, optstring, longopts, idx, true)
294}