rs-rich 0.0.9

A faithful Rust port of the Python `rich` terminal-rendering library
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
462
//! Box-drawing character sets.
//!
//! Port of upstream `rich/box.py`. A [`Box`] is parsed from an 8-line template
//! (exactly as upstream), giving named access to every corner, edge, and
//! junction. Panels, rules, and (later) tables draw their borders from these.
//!
//! All of upstream's built-in boxes are provided, along with [`Box::substitute`]
//! — the platform-dependent fallback applied on legacy Windows consoles (fancy
//! boxes → `SQUARE`) and non-UTF-8 terminals (→ `ASCII`).

/// Which divider a [`Box::get_row`] draws.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RowLevel {
    /// Separator below the header (`head_row_*`).
    Head,
    /// Separator between body rows (`row_*`).
    Row,
    /// Separator above the footer (`foot_row_*`).
    Foot,
    /// A blank row between body rows: `mid_left`, spaces, `mid_vertical`,
    /// `mid_right` (upstream's `level="mid"`, drawn by `Table(leading=…)`).
    Mid,
}

/// A set of box-drawing characters. Mirrors `rich.box.Box`.
///
/// The field names match upstream's 8×4 grid:
/// ```text
/// top_left    top              top_divider     top_right
/// head_left   (space)          head_vertical   head_right
/// head_row_left head_row_horizontal head_row_cross head_row_right
/// mid_left    (space)          mid_vertical    mid_right
/// row_left    row_horizontal   row_cross       row_right
/// foot_row_left foot_row_horizontal foot_row_cross foot_row_right
/// foot_left   (space)          foot_vertical   foot_right
/// bottom_left bottom           bottom_divider  bottom_right
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Box {
    pub top_left: char,
    pub top: char,
    pub top_divider: char,
    pub top_right: char,

    pub head_left: char,
    pub head_vertical: char,
    pub head_right: char,

    pub head_row_left: char,
    pub head_row_horizontal: char,
    pub head_row_cross: char,
    pub head_row_right: char,

    pub mid_left: char,
    pub mid_vertical: char,
    pub mid_right: char,

    pub row_left: char,
    pub row_horizontal: char,
    pub row_cross: char,
    pub row_right: char,

    pub foot_row_left: char,
    pub foot_row_horizontal: char,
    pub foot_row_cross: char,
    pub foot_row_right: char,

    pub foot_left: char,
    pub foot_vertical: char,
    pub foot_right: char,

    pub bottom_left: char,
    pub bottom: char,
    pub bottom_divider: char,
    pub bottom_right: char,
}

impl Box {
    /// Parse a box from the 8-line, 4-column template (as upstream does).
    ///
    /// Panics at const-eval time if the template is malformed, so the built-in
    /// constants are validated when the crate compiles.
    const fn parse(template: &str) -> Box {
        let rows = split_rows(template);
        Box {
            top_left: rows[0][0],
            top: rows[0][1],
            top_divider: rows[0][2],
            top_right: rows[0][3],

            head_left: rows[1][0],
            head_vertical: rows[1][2],
            head_right: rows[1][3],

            head_row_left: rows[2][0],
            head_row_horizontal: rows[2][1],
            head_row_cross: rows[2][2],
            head_row_right: rows[2][3],

            mid_left: rows[3][0],
            mid_vertical: rows[3][2],
            mid_right: rows[3][3],

            row_left: rows[4][0],
            row_horizontal: rows[4][1],
            row_cross: rows[4][2],
            row_right: rows[4][3],

            foot_row_left: rows[5][0],
            foot_row_horizontal: rows[5][1],
            foot_row_cross: rows[5][2],
            foot_row_right: rows[5][3],

            foot_left: rows[6][0],
            foot_vertical: rows[6][2],
            foot_right: rows[6][3],

            bottom_left: rows[7][0],
            bottom: rows[7][1],
            bottom_divider: rows[7][2],
            bottom_right: rows[7][3],
        }
    }

    /// The top border for the given column `widths`. Port of `Box.get_top`.
    /// `edge` controls whether the left/right corner glyphs are drawn.
    pub fn get_top(&self, widths: &[usize], edge: bool) -> String {
        let mut parts = String::new();
        if edge {
            parts.push(self.top_left);
        }
        let last = widths.len().saturating_sub(1);
        for (index, &width) in widths.iter().enumerate() {
            for _ in 0..width {
                parts.push(self.top);
            }
            if index != last {
                parts.push(self.top_divider);
            }
        }
        if edge {
            parts.push(self.top_right);
        }
        parts
    }

    /// A horizontal divider row between columns at a given `level`. Port of
    /// `Box.get_row`. `edge` controls whether the left/right glyphs are drawn.
    pub fn get_row(&self, widths: &[usize], level: RowLevel, edge: bool) -> String {
        let (left, horizontal, cross, right) = match level {
            RowLevel::Head => (
                self.head_row_left,
                self.head_row_horizontal,
                self.head_row_cross,
                self.head_row_right,
            ),
            RowLevel::Row => (
                self.row_left,
                self.row_horizontal,
                self.row_cross,
                self.row_right,
            ),
            RowLevel::Foot => (
                self.foot_row_left,
                self.foot_row_horizontal,
                self.foot_row_cross,
                self.foot_row_right,
            ),
            RowLevel::Mid => (self.mid_left, ' ', self.mid_vertical, self.mid_right),
        };
        let mut parts = String::new();
        if edge {
            parts.push(left);
        }
        let last = widths.len().saturating_sub(1);
        for (index, &width) in widths.iter().enumerate() {
            for _ in 0..width {
                parts.push(horizontal);
            }
            if index != last {
                parts.push(cross);
            }
        }
        if edge {
            parts.push(right);
        }
        parts
    }

    /// Return a version of this box safe for the target terminal. Port of
    /// `Box.substitute`.
    ///
    /// On a legacy Windows console (`legacy_windows` + `safe`), the fancy boxes
    /// that legacy code pages can't draw — `ROUNDED`, `HEAVY`, `HEAVY_HEAD` —
    /// fall back to `SQUARE` (`DOUBLE`/`SQUARE`/`MINIMAL` are kept). On a
    /// non-UTF-8 terminal (`ascii_only`), any non-ASCII box becomes `ASCII`.
    pub fn substitute(&self, legacy_windows: bool, safe: bool, ascii_only: bool) -> Box {
        let mut result = *self;
        if legacy_windows && safe && (result == ROUNDED || result == HEAVY || result == HEAVY_HEAD)
        {
            result = SQUARE;
        }
        if ascii_only && !result.is_ascii() {
            result = ASCII;
        }
        result
    }

    /// Whether every glyph is ASCII. Upstream passes `ascii=True` to exactly
    /// the built-in boxes drawn in ASCII (`ASCII`, `ASCII2`,
    /// `ASCII_DOUBLE_HEAD`, `MARKDOWN`), which `substitute` keeps on an
    /// ASCII-only terminal.
    pub fn is_ascii(&self) -> bool {
        [
            self.top_left,
            self.top,
            self.top_divider,
            self.top_right,
            self.head_left,
            self.head_vertical,
            self.head_right,
            self.head_row_left,
            self.head_row_horizontal,
            self.head_row_cross,
            self.head_row_right,
            self.mid_left,
            self.mid_vertical,
            self.mid_right,
            self.row_left,
            self.row_horizontal,
            self.row_cross,
            self.row_right,
            self.foot_row_left,
            self.foot_row_horizontal,
            self.foot_row_cross,
            self.foot_row_right,
            self.foot_left,
            self.foot_vertical,
            self.foot_right,
            self.bottom_left,
            self.bottom,
            self.bottom_divider,
            self.bottom_right,
        ]
        .iter()
        .all(char::is_ascii)
    }

    /// If this box draws its header border with special characters, the most
    /// similar box that does not; otherwise the box itself. Port of
    /// `Box.get_plain_headed_box`: a table without a header draws with it.
    pub fn get_plain_headed_box(&self) -> Box {
        match *self {
            b if b == HEAVY_HEAD || b == SQUARE_DOUBLE_HEAD => SQUARE,
            b if b == MINIMAL_DOUBLE_HEAD || b == MINIMAL_HEAVY_HEAD => MINIMAL,
            b if b == ASCII_DOUBLE_HEAD => ASCII2,
            other => other,
        }
    }

    /// The bottom border for the given column `widths`. Port of `Box.get_bottom`.
    /// `edge` controls whether the left/right corner glyphs are drawn.
    pub fn get_bottom(&self, widths: &[usize], edge: bool) -> String {
        let mut parts = String::new();
        if edge {
            parts.push(self.bottom_left);
        }
        let last = widths.len().saturating_sub(1);
        for (index, &width) in widths.iter().enumerate() {
            for _ in 0..width {
                parts.push(self.bottom);
            }
            if index != last {
                parts.push(self.bottom_divider);
            }
        }
        if edge {
            parts.push(self.bottom_right);
        }
        parts
    }
}

/// Split an 8-line template into an `[8][4]` grid of chars (const-eval helper).
const fn split_rows(template: &str) -> [[char; 4]; 8] {
    let bytes = template.as_bytes();
    let mut rows = [[' '; 4]; 8];
    // We iterate chars manually because box glyphs are multi-byte UTF-8 and the
    // template has a fixed shape: 4 columns per line, newline-separated.
    let mut i = 0usize; // byte index
    let mut row = 0usize;
    let mut col = 0usize;
    while i < bytes.len() {
        let (ch, width) = next_char(bytes, i);
        if ch == '\n' {
            row += 1;
            col = 0;
            i += width;
            continue;
        }
        if row < 8 && col < 4 {
            rows[row][col] = ch;
        }
        col += 1;
        i += width;
    }
    rows
}

/// Decode one UTF-8 char starting at `bytes[i]`, returning it and its byte len.
/// A small const-fn UTF-8 decoder (std's `chars()` isn't const).
const fn next_char(bytes: &[u8], i: usize) -> (char, usize) {
    let b0 = bytes[i];
    if b0 < 0x80 {
        (b0 as char, 1)
    } else if b0 >> 5 == 0b110 {
        let cp = ((b0 as u32 & 0x1f) << 6) | (bytes[i + 1] as u32 & 0x3f);
        (char_from_u32(cp), 2)
    } else if b0 >> 4 == 0b1110 {
        let cp = ((b0 as u32 & 0x0f) << 12)
            | ((bytes[i + 1] as u32 & 0x3f) << 6)
            | (bytes[i + 2] as u32 & 0x3f);
        (char_from_u32(cp), 3)
    } else {
        let cp = ((b0 as u32 & 0x07) << 18)
            | ((bytes[i + 1] as u32 & 0x3f) << 12)
            | ((bytes[i + 2] as u32 & 0x3f) << 6)
            | (bytes[i + 3] as u32 & 0x3f);
        (char_from_u32(cp), 4)
    }
}

const fn char_from_u32(cp: u32) -> char {
    match char::from_u32(cp) {
        Some(c) => c,
        None => '\u{fffd}',
    }
}

// ── Built-in boxes (subset of upstream `rich/box.py`) ──

pub const ASCII: Box = Box::parse("+--+\n| ||\n|-+|\n| ||\n|-+|\n|-+|\n| ||\n+--+\n");

pub const SQUARE: Box = Box::parse("┌─┬┐\n│ ││\n├─┼┤\n│ ││\n├─┼┤\n├─┼┤\n│ ││\n└─┴┘\n");

pub const ROUNDED: Box = Box::parse("╭─┬╮\n│ ││\n├─┼┤\n│ ││\n├─┼┤\n├─┼┤\n│ ││\n╰─┴╯\n");

pub const HEAVY: Box = Box::parse("┏━┳┓\n┃ ┃┃\n┣━╋┫\n┃ ┃┃\n┣━╋┫\n┣━╋┫\n┃ ┃┃\n┗━┻┛\n");

/// The default `Table` box: heavy top border + head separator, light body.
pub const HEAVY_HEAD: Box = Box::parse("┏━┳┓\n┃ ┃┃\n┡━╇┩\n│ ││\n├─┼┤\n├─┼┤\n│ ││\n└─┴┘\n");

pub const DOUBLE: Box = Box::parse("╔═╦╗\n║ ║║\n╠═╬╣\n║ ║║\n╠═╬╣\n╠═╬╣\n║ ║║\n╚═╩╝\n");

pub const MINIMAL: Box = Box::parse("  ╷ \n  │ \n╶─┼╴\n  │ \n╶─┼╴\n╶─┼╴\n  │ \n  ╵ \n");

pub const ASCII2: Box = Box::parse("+-++\n| ||\n+-++\n| ||\n+-++\n+-++\n| ||\n+-++\n");

pub const ASCII_DOUBLE_HEAD: Box = Box::parse("+-++\n| ||\n+=++\n| ||\n+-++\n+-++\n| ||\n+-++\n");

pub const SQUARE_DOUBLE_HEAD: Box = Box::parse("┌─┬┐\n│ ││\n╞═╪╡\n│ ││\n├─┼┤\n├─┼┤\n│ ││\n└─┴┘\n");

pub const MINIMAL_HEAVY_HEAD: Box = Box::parse("  ╷ \n  │ \n╺━┿╸\n  │ \n╶─┼╴\n╶─┼╴\n  │ \n  ╵ \n");

pub const MINIMAL_DOUBLE_HEAD: Box = Box::parse("  ╷ \n  │ \n ═╪ \n  │ \n ─┼ \n ─┼ \n  │ \n  ╵ \n");

/// A fully blank box (all spaces): no visible borders, though its border
/// lines still take up rows. Not in upstream, which uses `box=None` for a
/// table without borders.
pub const NONE: Box = Box::parse("    \n    \n    \n    \n    \n    \n    \n    \n");

/// A boxless table with a light head/foot rule. Used by Markdown tables.
pub const SIMPLE: Box = Box::parse("    \n    \n ── \n    \n    \n ── \n    \n    \n");

pub const SIMPLE_HEAD: Box = Box::parse("    \n    \n ── \n    \n    \n    \n    \n    \n");

pub const SIMPLE_HEAVY: Box = Box::parse("    \n    \n ━━ \n    \n    \n ━━ \n    \n    \n");

pub const HORIZONTALS: Box = Box::parse(" ── \n    \n ── \n    \n ── \n ── \n    \n ── \n");

pub const HEAVY_EDGE: Box = Box::parse("┏━┯┓\n┃ │┃\n┠─┼┨\n┃ │┃\n┠─┼┨\n┠─┼┨\n┃ │┃\n┗━┷┛\n");

pub const DOUBLE_EDGE: Box = Box::parse("╔═╤╗\n║ │║\n╟─┼╢\n║ │║\n╟─┼╢\n╟─┼╢\n║ │║\n╚═╧╝\n");

/// The box Markdown tables use for GFM output (pipes + a light head rule).
pub const MARKDOWN: Box = Box::parse("    \n| ||\n|-||\n| ||\n|-||\n|-||\n| ||\n    \n");

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

    #[test]
    fn rounded_corners() {
        assert_eq!(ROUNDED.top_left, '╭');
        assert_eq!(ROUNDED.top_right, '╮');
        assert_eq!(ROUNDED.bottom_left, '╰');
        assert_eq!(ROUNDED.bottom_right, '╯');
        assert_eq!(ROUNDED.top, '─');
        assert_eq!(ROUNDED.mid_left, '│');
        assert_eq!(ROUNDED.mid_right, '│');
    }

    #[test]
    fn square_and_ascii() {
        assert_eq!(SQUARE.top_left, '┌');
        assert_eq!(ASCII.top_left, '+');
        assert_eq!(ASCII.top, '-');
        assert_eq!(ASCII.mid_left, '|');
    }

    #[test]
    fn get_top_and_bottom_single_column() {
        assert_eq!(ROUNDED.get_top(&[3], true), "╭───╮");
        assert_eq!(ROUNDED.get_bottom(&[3], true), "╰───╯");
        // Without edges, the corners are omitted.
        assert_eq!(ROUNDED.get_top(&[3], false), "───");
        assert_eq!(SQUARE.get_row(&[2, 2], RowLevel::Head, false), "──┼──");
    }

    #[test]
    fn additional_boxes_parse() {
        // SIMPLE / MARKDOWN have blank edges and a head rule.
        assert_eq!(SIMPLE.top_left, ' ');
        assert_eq!(SIMPLE.head_row_horizontal, '─');
        assert_eq!(SIMPLE_HEAVY.head_row_horizontal, '━');
        assert_eq!(MARKDOWN.mid_left, '|');
        assert_eq!(MARKDOWN.head_row_horizontal, '-');
        assert_eq!(DOUBLE_EDGE.top_left, '╔');
        assert_eq!(DOUBLE_EDGE.mid_vertical, '│');
        assert_eq!(HEAVY_EDGE.top_left, '┏');
        assert_eq!(SQUARE_DOUBLE_HEAD.head_row_horizontal, '═');
        assert_eq!(ASCII2.head_row_cross, '+');
    }

    #[test]
    fn plain_headed_boxes() {
        assert_eq!(HEAVY_HEAD.get_plain_headed_box(), SQUARE);
        assert_eq!(SQUARE_DOUBLE_HEAD.get_plain_headed_box(), SQUARE);
        assert_eq!(MINIMAL_DOUBLE_HEAD.get_plain_headed_box(), MINIMAL);
        assert_eq!(MINIMAL_HEAVY_HEAD.get_plain_headed_box(), MINIMAL);
        assert_eq!(ASCII_DOUBLE_HEAD.get_plain_headed_box(), ASCII2);
        assert_eq!(ROUNDED.get_plain_headed_box(), ROUNDED);
    }

    #[test]
    fn substitute_legacy_and_ascii() {
        // Legacy Windows: fancy → SQUARE; DOUBLE/SQUARE kept.
        assert_eq!(ROUNDED.substitute(true, true, false), SQUARE);
        assert_eq!(HEAVY.substitute(true, true, false), SQUARE);
        assert_eq!(HEAVY_HEAD.substitute(true, true, false), SQUARE);
        assert_eq!(DOUBLE.substitute(true, true, false), DOUBLE);
        assert_eq!(SQUARE.substitute(true, true, false), SQUARE);
        // `safe=false` disables the legacy fallback.
        assert_eq!(ROUNDED.substitute(true, false, false), ROUNDED);
        // Non-UTF-8: anything non-ASCII → ASCII.
        assert_eq!(ROUNDED.substitute(false, true, true), ASCII);
        assert_eq!(DOUBLE.substitute(false, true, true), ASCII);
        assert_eq!(ASCII.substitute(false, true, true), ASCII);
        // No flags → unchanged.
        assert_eq!(ROUNDED.substitute(false, true, false), ROUNDED);
    }
}