ztmux 3.7.0

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
// Copyright (c) 1989, 1993
// 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 core::ffi::c_int;

// documentation from vis(3bsd)
bitflags::bitflags! {
    #[repr(transparent)]
    #[derive(Copy, Clone, Eq, PartialEq)]
    pub(crate) struct vis_flags: i32 {
        /// Use a three digit octal sequence. The form is '\ddd' where each 'd' represents an octal
        /// digit.
        ///
        /// tmux-rs considers this flag to be set unconditionally.
        const VIS_OCTAL   = 0x0001;

        /// Use C-style backslash sequences to represent standard non-printable characters.
        /// The following sequences are used to represent the indicated characters:
        /// \a - BEL (007)
        /// \b - BS  (010)
        /// \t - HT  (011)
        /// \n - NL  (012)
        /// \v - VT  (013)
        /// \f - NP  (014)
        /// \r - CR  (015)
        /// \s - SP  (040)
        /// \0 - NUL (000)
        ///
        /// tmux-rs considers this flag to be set unconditionally.
        const VIS_CSTYLE  = 0x0002;

        /// encode tab
        const VIS_TAB     = 0x0008;

        /// encode newline
        const VIS_NL      = 0x0010;

        /// inhibit the doubling of backslashes and the backslash before the default format
        /// (that is, control characters are represented by ‘^C’ and meta characters as ‘M-C’).
        /// with this flag set, the encoding is ambiguous and non-invertible.
        const VIS_NOSLASH = 0x0040;

        /// encode double quote
        const VIS_DQ      = 0x0200;
    }
}

/// copies into dst a string which represents the character c. If c needs no encoding, it is copied in unaltered.
/// The string is null terminated, and a pointer to the end of the string is returned.
pub unsafe fn vis_(dst: *mut u8, c: c_int, flag: vis_flags, nextc: c_int) -> *mut u8 {
    unsafe {
        match c as u8 {
            b'\0' if !matches!(nextc as u8, b'0'..=b'7') => encode_cstyle(dst, b'0'),
            b'\t' if flag.intersects(vis_flags::VIS_TAB) => encode_cstyle(dst, b't'),
            b'\n' if flag.intersects(vis_flags::VIS_NL) => encode_cstyle(dst, b'n'),
            b'\\' if !flag.intersects(vis_flags::VIS_NOSLASH) => encode_cstyle(dst, b'\\'),
            b'"' if flag.intersects(vis_flags::VIS_DQ) => encode_cstyle(dst, b'"'),
            7..9 | 11..14 => {
                const CSTYLE: [u8; 7] = [b'a', b'b', 0, 0, b'v', b'f', b'r'];
                encode_cstyle(dst, CSTYLE[c as usize - 7])
            }
            0..7 | 14..32 | 127.. => encode_octal(dst, c),
            _ => encode_passthrough(dst, c),
        }
    }
}

pub fn vis__(dst: &mut Vec<u8>, c: c_int, flag: vis_flags, nextc: c_int) {
    match c as u8 {
        b'\0' if !matches!(nextc as u8, b'0'..=b'7') => encode_cstyle_(dst, b'0'),
        b'\t' if flag.intersects(vis_flags::VIS_TAB) => encode_cstyle_(dst, b't'),
        b'\n' if flag.intersects(vis_flags::VIS_NL) => encode_cstyle_(dst, b'n'),
        b'\\' if !flag.intersects(vis_flags::VIS_NOSLASH) => encode_cstyle_(dst, b'\\'),
        b'"' if flag.intersects(vis_flags::VIS_DQ) => encode_cstyle_(dst, b'"'),
        7..9 | 11..14 => {
            const CSTYLE: [u8; 7] = [b'a', b'b', 0, 0, b'v', b'f', b'r'];
            encode_cstyle_(dst, CSTYLE[c as usize - 7]);
        }
        0..7 | 14..32 | 127.. => encode_octal_(dst, c),
        _ => encode_passthrough_(dst, c),
    }
}

#[inline]
unsafe fn encode_passthrough(dst: *mut u8, ch: i32) -> *mut u8 {
    unsafe {
        *dst = ch as u8;
        *dst.add(1) = b'\0';
        dst.add(1)
    }
}

#[inline]
fn encode_passthrough_(dst: &mut Vec<u8>, ch: i32) {
    dst.push(ch as u8);
}

#[inline]
unsafe fn encode_cstyle(dst: *mut u8, ch: u8) -> *mut u8 {
    unsafe {
        *dst = b'\\';
        *dst.add(1) = ch;
        *dst.add(2) = b'\0';
        dst.add(2)
    }
}

#[inline]
fn encode_cstyle_(dst: &mut Vec<u8>, ch: u8) {
    dst.push(b'\\');
    dst.push(ch);
}

#[inline]
unsafe fn encode_octal(dst: *mut u8, c: i32) -> *mut u8 {
    unsafe {
        let c = c as u8;
        let ones_place = c % 8;
        let eights_place = (c / 8) % 8;
        let sixty_four_place = c / 64;
        *dst = b'\\';
        *dst.add(1) = sixty_four_place + b'0';
        *dst.add(2) = eights_place + b'0';
        *dst.add(3) = ones_place + b'0';
        *dst.add(4) = b'\0';
        dst.add(4)
    }
}

fn encode_octal_(dst: &mut Vec<u8>, c: i32) {
    let c = c as u8;
    let ones_place = c % 8;
    let eights_place = (c / 8) % 8;
    let sixty_four_place = c / 64;
    dst.push(b'\\');
    dst.push(sixty_four_place + b'0');
    dst.push(eights_place + b'0');
    dst.push(ones_place + b'0');
}

/// C `vendor/tmux/compat/vis.c:155`: `int strvis(char *dst, const char *src, int flag)`
pub unsafe fn strvis(mut dst: *mut u8, mut src: *const u8, flag: vis_flags) -> i32 {
    unsafe {
        let start = dst;

        while *src != 0 {
            dst = vis_(dst, *src as i32, flag, *src.add(1) as i32);
            src = src.add(1);
        }
        *dst = 0;

        dst.offset_from(start) as i32
    }
}

/// C `vendor/tmux/compat/vis.c:167`: `int strnvis(char *dst, const char *src, size_t siz, int flag)`
pub unsafe fn strnvis(mut dst: *mut u8, mut src: *const u8, dlen: usize, flag: vis_flags) -> i32 {
    unsafe {
        let mut i = 0;

        while *src != 0 && i < dlen {
            let tmp = vis_(dst, *src as i32, flag, *src.add(1) as i32);
            i += dst.offset_from_unsigned(dst);
            dst = tmp;
            src = src.add(1);
        }
        *dst = 0;

        i as i32
    }
}

/// C `vendor/tmux/compat/vis.c:210`: `int stravis(char **outp, const char *src, int flag)`
pub unsafe fn stravis(outp: *mut *mut u8, src: *const u8, flag: vis_flags) -> i32 {
    unsafe {
        let buf: *mut u8 = libc::calloc(4, crate::libc::strlen(src) + 1).cast();
        if buf.is_null() {
            return -1;
        }
        let len = strvis(buf, src, flag);
        let serrno = crate::errno!();
        *outp = libc::realloc(buf.cast(), len as usize + 1).cast();
        if (*outp).is_null() {
            *outp = buf;
            crate::errno!() = serrno;
        }

        len
    }
}

/// C `vendor/tmux/compat/vis.c:57`: `char *vis(char *dst, int c, int flag, int nextc)`
pub unsafe fn vis(dst: *mut u8, c: c_int, flag: vis_flags, nextc: c_int) -> *mut u8 {
    unsafe { vis_(dst, c, flag, nextc) }
}

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

    #[test]
    fn test_vis() {
        let mut c_dst_arr: [u8; 16] = [0; 16];
        let mut rs_dst_arr: [u8; 16] = [0; 16];

        let c_dst = &raw mut c_dst_arr as *mut u8;
        let rs_dst = &raw mut rs_dst_arr as *mut u8;

        unsafe {
            for f1 in [
                vis_flags::VIS_OCTAL,
                vis_flags::VIS_CSTYLE,
                vis_flags::VIS_OCTAL | vis_flags::VIS_CSTYLE,
            ] {
                for f2 in [
                    vis_flags::VIS_TAB | vis_flags::VIS_NL,
                    vis_flags::VIS_TAB,
                    vis_flags::VIS_NL,
                    vis_flags::VIS_DQ,
                    vis_flags::VIS_NOSLASH,
                ] {
                    for ch in 0..=u8::MAX {
                        for nextc in [b'\0' as i32, b'0' as i32] {
                            let flag = f1 | f2;
                            let rs_out = vis_(rs_dst, ch as i32, flag, nextc);
                            let c_out = vis(c_dst, ch as i32, flag, nextc);

                            assert_eq!(
                                c_dst_arr,
                                rs_dst_arr,
                                "mismatch when encoding vis(_, _, _, {ch}) => {} != {}",
                                crate::_s(c_dst),
                                crate::_s(rs_dst)
                            );

                            assert_eq!(rs_out.offset_from(rs_dst), c_out.offset_from(c_dst));

                            c_dst_arr.fill(0);
                            rs_dst_arr.fill(0);
                        }
                    }
                }
            }
        }
    }

    const NONE: vis_flags = vis_flags::empty();

    // Encode a single character with vis_ and return the bytes written (the
    // routine also NUL-terminates and returns a pointer to that NUL, so the
    // length is the pointer delta).
    unsafe fn enc(c: i32, flag: vis_flags, nextc: i32) -> Vec<u8> {
        unsafe {
            let mut buf = [0u8; 8];
            let end = vis_(buf.as_mut_ptr(), c, flag, nextc);
            let len = end.offset_from(buf.as_ptr()) as usize;
            buf[..len].to_vec()
        }
    }

    #[test]
    fn test_vis_printable_passthrough() {
        unsafe {
            // Graphic ASCII passes through unaltered.
            assert_eq!(enc(b'A' as i32, NONE, 0), b"A");
            assert_eq!(enc(b'z' as i32, NONE, 0), b"z");
            assert_eq!(enc(b'~' as i32, NONE, 0), b"~");
            // This port passes a literal space through (it is not in any of the
            // control/octal ranges of vis_, vis.rs:75-86).
            assert_eq!(enc(b' ' as i32, NONE, 0), b" ");
        }
    }

    #[test]
    fn test_vis_backslash() {
        unsafe {
            // Default: backslash is doubled (vis.c:61).
            assert_eq!(enc(b'\\' as i32, NONE, 0), b"\\\\");
            // VIS_NOSLASH inhibits the doubling -> single literal backslash.
            assert_eq!(enc(b'\\' as i32, vis_flags::VIS_NOSLASH, 0), b"\\");
        }
    }

    #[test]
    fn test_vis_double_quote() {
        unsafe {
            // VIS_DQ escapes '"' as '\"' (vis.c:60).
            assert_eq!(enc(b'"' as i32, vis_flags::VIS_DQ, 0), b"\\\"");
            // Without VIS_DQ the quote is a plain printable.
            assert_eq!(enc(b'"' as i32, NONE, 0), b"\"");
        }
    }

    #[test]
    fn test_vis_tab() {
        unsafe {
            // VIS_TAB -> C-style "\t"; without it the tab passes through raw.
            assert_eq!(enc(b'\t' as i32, vis_flags::VIS_TAB, 0), b"\\t");
            assert_eq!(enc(b'\t' as i32, NONE, 0), b"\t");
        }
    }

    #[test]
    fn test_vis_newline() {
        unsafe {
            // VIS_NL -> "\n"; without it the newline passes through raw.
            assert_eq!(enc(b'\n' as i32, vis_flags::VIS_NL, 0), b"\\n");
            assert_eq!(enc(b'\n' as i32, NONE, 0), b"\n");
        }
    }

    #[test]
    fn test_vis_cstyle_controls() {
        unsafe {
            // The named C-style escapes (vis.c:82-93), always active in this
            // port regardless of flags.
            assert_eq!(enc(0x07, NONE, 0), b"\\a"); // BEL
            assert_eq!(enc(0x08, NONE, 0), b"\\b"); // BS
            assert_eq!(enc(0x0b, NONE, 0), b"\\v"); // VT
            assert_eq!(enc(0x0c, NONE, 0), b"\\f"); // FF
            assert_eq!(enc(0x0d, NONE, 0), b"\\r"); // CR
        }
    }

    #[test]
    fn test_vis_nul() {
        unsafe {
            // NUL with a non-octal following char -> short "\0" form (vis.c:102).
            assert_eq!(enc(0, NONE, 0), b"\\0");
            assert_eq!(enc(0, NONE, b'x' as i32), b"\\0");
            // NUL followed by an octal digit must use the full three-digit octal
            // so the decoder can't merge the digits (vis.c:105 doubles the 0;
            // this port emits the octal escape instead).
            assert_eq!(enc(0, NONE, b'0' as i32), b"\\000");
            assert_eq!(enc(0, NONE, b'7' as i32), b"\\000");
        }
    }

    #[test]
    fn test_vis_octal_ranges() {
        unsafe {
            // Non-named control chars and all high-bit bytes -> three-digit
            // octal (vis.rs:85).
            assert_eq!(enc(0x01, NONE, 0), b"\\001");
            assert_eq!(enc(0x06, NONE, 0), b"\\006");
            assert_eq!(enc(0x0e, NONE, 0), b"\\016");
            assert_eq!(enc(0x1f, NONE, 0), b"\\037");
            assert_eq!(enc(0x7f, NONE, 0), b"\\177"); // DEL
            assert_eq!(enc(0x80, NONE, 0), b"\\200");
            assert_eq!(enc(0xff, NONE, 0), b"\\377");
        }
    }

    #[test]
    fn test_strvis_literals_and_length() {
        unsafe {
            let mut dst = [0u8; 32];
            let ret = strvis(dst.as_mut_ptr(), crate::c!("abc"), NONE);
            assert_eq!(ret, 3);
            assert_eq!(&dst[..4], b"abc\0");
        }
    }

    #[test]
    fn test_strvis_tab_and_backslash() {
        unsafe {
            // "a<TAB>b" with VIS_TAB -> "a\tb" (4 visible bytes).
            let mut dst = [0u8; 32];
            let ret = strvis(dst.as_mut_ptr(), crate::c!("a\tb"), vis_flags::VIS_TAB);
            assert_eq!(ret, 4);
            assert_eq!(&dst[..5], b"a\\tb\0");

            // A literal backslash in the source is doubled.
            let mut dst2 = [0u8; 32];
            let ret2 = strvis(dst2.as_mut_ptr(), crate::c!("a\\b"), NONE);
            assert_eq!(ret2, 4);
            assert_eq!(&dst2[..5], b"a\\\\b\0");
        }
    }

    #[test]
    fn test_strvis_control_expands_to_octal() {
        unsafe {
            // A lone 0x01 expands to the four-byte octal escape "\001".
            let mut dst = [0u8; 32];
            let ret = strvis(dst.as_mut_ptr(), crate::c!("\x01"), NONE);
            assert_eq!(ret, 4);
            assert_eq!(&dst[..5], b"\\001\0");
        }
    }

    #[test]
    fn test_strnvis_ignores_dlen() {
        // DISCREPANCY vs BSD strnvis: C writes no more than siz-1 bytes and
        // returns the length needed to fully encode (vis.c:167). This port's
        // length accumulator adds `dst.offset_from_unsigned(dst)`, which is
        // always 0 (vis.rs:186), so `i` never grows: the dlen bound is never
        // enforced and the return value is always 0. Here dlen=2 but all three
        // source bytes are still written. Asserting ACTUAL (buggy) behavior in
        // a buffer large enough that the missing bound is not a memory hazard.
        unsafe {
            let mut dst = [0u8; 32];
            let ret = strnvis(dst.as_mut_ptr(), crate::c!("abc"), 2, NONE);
            assert_eq!(ret, 0);
            assert_eq!(&dst[..4], b"abc\0");
        }
    }
}