ztmux 3.7.20

A Rust port of tmux — the full terminal multiplexer, server and client
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
// Copyright (c) 1987, 1993, 1994
// The Regents of the University of California.  All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
// 3. Neither the name of the University nor the names of its contributors
//    may be used to endorse or promote products derived from this software
//    without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE.
use crate::*;

// originally generated by c2rust
// refactored to remove the BSD prefix, we don't need to worry about collisions with C

pub static mut OPTERR: i32 = 1;
pub static mut OPTIND: i32 = 1;
pub static mut OPTOPT: u8 = 0;
pub static mut OPTRESET: i32 = 0;
pub static mut OPTARG: *mut u8 = null_mut();

/// C `vendor/tmux/compat/getopt_long.c:535`: `int getopt(int nargc, char * const *nargv, const char *options)`
pub unsafe fn getopt(nargc: i32, nargv: *const *mut u8, ostr: *const u8) -> Option<u8> {
    unsafe {
        static mut PLACE: *const u8 = c"".as_ptr().cast();
        let mut oli: *mut u8;
        if ostr.is_null() {
            return None;
        }
        if OPTRESET != 0 || *PLACE == 0 {
            OPTRESET = 0;
            if OPTIND >= nargc || {
                PLACE = *nargv.offset(OPTIND as isize);
                *PLACE != b'-'
            } {
                PLACE = c"".as_ptr().cast();
                return None;
            }
            if *PLACE.add(1) != 0 && {
                PLACE = PLACE.add(1);
                *PLACE == b'-'
            } {
                if *PLACE.add(1) != 0 {
                    return Some(b'?');
                }
                OPTIND += 1;
                PLACE = c"".as_ptr().cast();
                return None;
            }
        }
        let fresh0 = PLACE;
        PLACE = PLACE.add(1);
        OPTOPT = *fresh0;
        if OPTOPT == b':' || {
            oli = crate::libc::strchr(ostr, OPTOPT as i32);
            oli.is_null()
        } {
            if OPTOPT == b'-' {
                return None;
            }
            if *PLACE == 0 {
                OPTIND += 1;
            }
            if OPTERR != 0 && *ostr != b':' {
                let tmp = OPTOPT;
                eprintln!("ztmux: unknown option -- {}", tmp as char);
            }
            return Some(b'?');
        }
        oli = oli.add(1);
        if *oli != b':' {
            OPTARG = null_mut();
            if *PLACE == 0 {
                OPTIND += 1;
            }
        } else {
            if *PLACE != 0 {
                OPTARG = PLACE.cast_mut();
            } else {
                OPTIND += 1;
                if nargc <= OPTIND {
                    PLACE = c"".as_ptr().cast();
                    if *ostr == b':' {
                        return Some(b':');
                    }
                    if OPTERR != 0 {
                        let tmp = OPTOPT;
                        eprintln!("ztmux: option requires an argument -- {}", tmp as char);
                    }
                    return Some(b'?');
                } else {
                    OPTARG = *nargv.offset(OPTIND as isize);
                }
            }
            PLACE = c"".as_ptr().cast();
            OPTIND += 1;
        }

        Some(OPTOPT)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // The getopt globals (OPTIND/OPTARG/OPTOPT/OPTERR/OPTRESET) plus the
    // function-internal `PLACE` static are shared mutable state, exactly like
    // C's getopt(3). Serialize every test so parallel test threads can't clobber
    // each other's parse state.
    static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    /// Reset getopt state the way the C manual requires between independent
    /// argument vectors: `optreset = 1; optind = 1;`
    /// (see `vendor/tmux/compat/getopt_long.c` and getopt.c). We also silence
    /// error output via `OPTERR = 0` so the "unknown option" / "requires an
    /// argument" diagnostics don't spam the test log; the return values are
    /// unaffected by OPTERR.
    unsafe fn reset() {
        unsafe {
            OPTRESET = 1;
            OPTIND = 1;
            OPTERR = 0;
            OPTARG = null_mut();
            OPTOPT = 0;
        }
    }

    // Helper: run getopt once against an argv slice of `*mut u8`.
    unsafe fn go(argv: &[*mut u8], ostr: *const u8) -> Option<u8> {
        unsafe { getopt(argv.len() as i32, argv.as_ptr(), ostr) }
    }

    // Copy the mutable-static globals into locals so assert_eq!/assert! don't
    // form references to them (forbidden in edition 2024).
    unsafe fn optind() -> i32 {
        unsafe { OPTIND }
    }
    unsafe fn optopt() -> u8 {
        unsafe { OPTOPT }
    }
    unsafe fn optarg() -> *mut u8 {
        unsafe { OPTARG }
    }

    #[test]
    fn simple_option_string() {
        let _g = LOCK.lock().unwrap();
        unsafe {
            reset();
            // ostr "ab": both are flags with no argument.
            let argv: [*mut u8; 4] = [
                crate::c!("prog").cast_mut(),
                crate::c!("-a").cast_mut(),
                crate::c!("-b").cast_mut(),
                crate::c!("arg").cast_mut(),
            ];
            let ostr = crate::c!("ab");

            // "-a": flag consumed, optind advances past argv[1].
            assert_eq!(go(&argv, ostr), Some(b'a'));
            assert_eq!(optind(), 2);
            // "-b": flag consumed, optind advances past argv[2].
            assert_eq!(go(&argv, ostr), Some(b'b'));
            assert_eq!(optind(), 3);
            // argv[3] "arg" does not start with '-', so parsing stops (EOF).
            assert_eq!(go(&argv, ostr), None);
            // The simple BSD getopt does not permute; optind is left pointing
            // at the first non-option operand.
            assert_eq!(optind(), 3);
        }
    }

    #[test]
    fn clustered_flags() {
        let _g = LOCK.lock().unwrap();
        unsafe {
            reset();
            // "-ab" packs two flags into one word.
            let argv: [*mut u8; 2] =
                [crate::c!("prog").cast_mut(), crate::c!("-ab").cast_mut()];
            let ostr = crate::c!("ab");

            // First 'a': still more chars in the word, so optind stays put.
            assert_eq!(go(&argv, ostr), Some(b'a'));
            assert_eq!(optind(), 1);
            // Then 'b': word exhausted, optind advances.
            assert_eq!(go(&argv, ostr), Some(b'b'));
            assert_eq!(optind(), 2);
            assert_eq!(go(&argv, ostr), None);
        }
    }

    #[test]
    fn required_arg_separate_word() {
        let _g = LOCK.lock().unwrap();
        unsafe {
            reset();
            // ostr "a:b": -a takes an argument, -b is a flag.
            let argv: [*mut u8; 4] = [
                crate::c!("prog").cast_mut(),
                crate::c!("-a").cast_mut(),
                crate::c!("val").cast_mut(),
                crate::c!("-b").cast_mut(),
            ];
            let ostr = crate::c!("a:b");

            assert_eq!(go(&argv, ostr), Some(b'a'));
            // Argument taken from the following word; optind now past both.
            assert!(!optarg().is_null());
            assert_eq!(crate::libc::strcmp(optarg(), crate::c!("val")), 0);
            assert_eq!(optind(), 3);

            assert_eq!(go(&argv, ostr), Some(b'b'));
            assert_eq!(optind(), 4);
            assert_eq!(go(&argv, ostr), None);
        }
    }

    #[test]
    fn required_arg_attached() {
        let _g = LOCK.lock().unwrap();
        unsafe {
            reset();
            // "-aval": the argument is glued to the option letter.
            let argv: [*mut u8; 2] =
                [crate::c!("prog").cast_mut(), crate::c!("-aval").cast_mut()];
            let ostr = crate::c!("a:");

            assert_eq!(go(&argv, ostr), Some(b'a'));
            assert!(!optarg().is_null());
            assert_eq!(crate::libc::strcmp(optarg(), crate::c!("val")), 0);
            assert_eq!(optind(), 2);
            assert_eq!(go(&argv, ostr), None);
        }
    }

    #[test]
    fn unknown_option_returns_question_mark() {
        let _g = LOCK.lock().unwrap();
        unsafe {
            reset();
            let argv: [*mut u8; 2] =
                [crate::c!("prog").cast_mut(), crate::c!("-x").cast_mut()];
            let ostr = crate::c!("ab");

            // 'x' is not in "ab": BADCH ('?'), and optopt records the offender.
            assert_eq!(go(&argv, ostr), Some(b'?'));
            assert_eq!(optopt(), b'x');
            assert_eq!(optind(), 2);
            assert_eq!(go(&argv, ostr), None);
        }
    }

    #[test]
    fn missing_required_arg_default() {
        let _g = LOCK.lock().unwrap();
        unsafe {
            reset();
            // "-a" requires an argument but none follows -> BADCH ('?')
            // because the option string does not begin with ':'.
            let argv: [*mut u8; 2] =
                [crate::c!("prog").cast_mut(), crate::c!("-a").cast_mut()];
            let ostr = crate::c!("a:");

            assert_eq!(go(&argv, ostr), Some(b'?'));
            assert_eq!(optopt(), b'a');
        }
    }

    #[test]
    fn missing_required_arg_colon_ostr() {
        let _g = LOCK.lock().unwrap();
        unsafe {
            reset();
            // Leading ':' in the option string switches the missing-argument
            // return from '?' (BADCH) to ':' (BADARG).
            let argv: [*mut u8; 2] =
                [crate::c!("prog").cast_mut(), crate::c!("-a").cast_mut()];
            let ostr = crate::c!(":a:");

            assert_eq!(go(&argv, ostr), Some(b':'));
            assert_eq!(optopt(), b'a');
        }
    }

    #[test]
    fn double_dash_terminates() {
        let _g = LOCK.lock().unwrap();
        unsafe {
            reset();
            // "--" ends option processing; the following "-a" is an operand.
            let argv: [*mut u8; 3] = [
                crate::c!("prog").cast_mut(),
                crate::c!("--").cast_mut(),
                crate::c!("-a").cast_mut(),
            ];
            let ostr = crate::c!("a");

            // First call swallows "--" and reports EOF, leaving optind past it.
            assert_eq!(go(&argv, ostr), None);
            assert_eq!(optind(), 2);
        }
    }

    #[test]
    fn lone_dash_is_operand() {
        let _g = LOCK.lock().unwrap();
        unsafe {
            reset();
            // A bare "-" is a non-option operand (conventionally stdin), so
            // getopt returns EOF and does not advance optind.
            let argv: [*mut u8; 2] =
                [crate::c!("prog").cast_mut(), crate::c!("-").cast_mut()];
            let ostr = crate::c!("a");

            assert_eq!(go(&argv, ostr), None);
            assert_eq!(optind(), 1);
        }
    }

    #[test]
    fn no_permutation_stops_at_first_operand() {
        let _g = LOCK.lock().unwrap();
        unsafe {
            reset();
            // The BSD getopt(3) never permutes: once a non-option word is seen,
            // parsing stops and later options are NOT reordered/parsed.
            let argv: [*mut u8; 4] = [
                crate::c!("prog").cast_mut(),
                crate::c!("-a").cast_mut(),
                crate::c!("file").cast_mut(),
                crate::c!("-b").cast_mut(),
            ];
            let ostr = crate::c!("ab");

            assert_eq!(go(&argv, ostr), Some(b'a'));
            assert_eq!(optind(), 2);
            // Stops at "file"; "-b" is left unparsed.
            assert_eq!(go(&argv, ostr), None);
            assert_eq!(optind(), 2);
        }
    }

    #[test]
    fn null_option_string_returns_none() {
        let _g = LOCK.lock().unwrap();
        unsafe {
            reset();
            let argv: [*mut u8; 2] =
                [crate::c!("prog").cast_mut(), crate::c!("-a").cast_mut()];
            // A null option string is rejected immediately with EOF.
            assert_eq!(getopt(argv.len() as i32, argv.as_ptr(), null()), None);
        }
    }

    #[test]
    fn flag_clears_optarg() {
        let _g = LOCK.lock().unwrap();
        unsafe {
            reset();
            // A no-argument option resets OPTARG to null (getopt_long.c: the
            // non-':' branch sets optarg = NULL).
            OPTARG = crate::c!("stale").cast_mut();
            let argv: [*mut u8; 2] =
                [crate::c!("prog").cast_mut(), crate::c!("-a").cast_mut()];
            let ostr = crate::c!("a");
            assert_eq!(go(&argv, ostr), Some(b'a'));
            assert!(optarg().is_null());
        }
    }

    #[test]
    fn cluster_then_arg_option() {
        let _g = LOCK.lock().unwrap();
        unsafe {
            reset();
            // "-baval" with ostr "ba:": 'b' is a flag packed ahead of 'a',
            // whose argument is the remainder "val" glued in the same word.
            let argv: [*mut u8; 2] =
                [crate::c!("prog").cast_mut(), crate::c!("-baval").cast_mut()];
            let ostr = crate::c!("ba:");

            assert_eq!(go(&argv, ostr), Some(b'b'));
            // 'b' is mid-word, so optind has not advanced yet.
            assert_eq!(optind(), 1);
            assert_eq!(go(&argv, ostr), Some(b'a'));
            assert_eq!(crate::libc::strcmp(optarg(), crate::c!("val")), 0);
            assert_eq!(optind(), 2);
            assert_eq!(go(&argv, ostr), None);
        }
    }

    #[test]
    fn unknown_with_colon_ostr_still_badch() {
        let _g = LOCK.lock().unwrap();
        unsafe {
            reset();
            // A leading ':' only changes the *missing-argument* return to ':'.
            // An unknown option is still BADCH ('?'), not ':'.
            let argv: [*mut u8; 2] =
                [crate::c!("prog").cast_mut(), crate::c!("-x").cast_mut()];
            let ostr = crate::c!(":ab");
            assert_eq!(go(&argv, ostr), Some(b'?'));
            assert_eq!(optopt(), b'x');
        }
    }

    #[test]
    fn no_options_present_returns_none() {
        let _g = LOCK.lock().unwrap();
        unsafe {
            reset();
            // argv with only the program name and a bare operand: getopt reports
            // EOF at the first non-option word, optind left pointing at it.
            let argv: [*mut u8; 2] =
                [crate::c!("prog").cast_mut(), crate::c!("file").cast_mut()];
            let ostr = crate::c!("ab");
            assert_eq!(go(&argv, ostr), None);
            assert_eq!(optind(), 1);
        }
    }

    #[test]
    fn reset_reparses_second_vector() {
        let _g = LOCK.lock().unwrap();
        unsafe {
            reset();
            let ostr = crate::c!("ab");
            let argv1: [*mut u8; 2] =
                [crate::c!("prog").cast_mut(), crate::c!("-a").cast_mut()];
            assert_eq!(go(&argv1, ostr), Some(b'a'));
            assert_eq!(go(&argv1, ostr), None);

            // Independent second parse requires optreset=1; optind=1 (the C
            // manual's reset protocol). After it, "-b" is seen fresh.
            reset();
            let argv2: [*mut u8; 2] =
                [crate::c!("prog").cast_mut(), crate::c!("-b").cast_mut()];
            assert_eq!(go(&argv2, ostr), Some(b'b'));
            assert_eq!(optind(), 2);
            assert_eq!(go(&argv2, ostr), None);
        }
    }
}