Skip to main content

uncurses/renderer/
cost.rs

1//! Byte-length predictors for renderer ANSI plans.
2//!
3//! ## Category
4//!
5//! Cost functions mirror writer functions in [`crate::ansi::cursor`] and
6//! [`crate::ansi::screen`]. They let render planning compare equivalent cursor,
7//! erase, and scroll strategies without allocating formatted strings.
8//!
9//! The cursor planner owns cell-aware overwrite costs.
10//!
11//! ```
12//! use uncurses::ansi::cursor::write_cup;
13//! use uncurses::renderer::cost::cup_cost;
14//!
15//! let mut bytes = Vec::new();
16//! write_cup(&mut bytes, 3, 10).unwrap();
17//! assert_eq!(cup_cost(3, 10), bytes.len());
18//! ```
19//!
20//! ## Conventions
21//!
22//! Costs are byte counts for the exact 7-bit sequences emitted by this crate,
23//! including omitted default parameters such as `ESC [ A` for `CUU 1` and
24//! `ESC [ H` for home.
25//!
26//! ## Mode interaction
27//!
28//! The predictors do not change terminal modes. For mode-sensitive sequences,
29//! such as left/right margins requiring [`Mode::LEFT_RIGHT_MARGIN`](crate::ansi::mode::Mode::LEFT_RIGHT_MARGIN), the cost still describes only the bytes emitted.
30
31/// Bytes in a CSI introducer (`ESC [`).
32const CSI_LEN: usize = 2;
33
34/// Number of decimal digits in a `u16`. Branchy table — faster than
35/// `ilog10` on the small range we feed it (cursor coordinates,
36/// repeat counts).
37pub const fn digit_count(n: u16) -> usize {
38    if n < 10 {
39        1
40    } else if n < 100 {
41        2
42    } else if n < 1000 {
43        3
44    } else if n < 10000 {
45        4
46    } else {
47        5
48    }
49}
50
51/// Cost of a single-parameter CSI where `n == 1` omits the parameter
52/// (the writer emits `ESC [ X` instead of `ESC [ 1 X`). Final byte
53/// contributes 1.
54///
55/// Shape: `\x1b[X` for `n <= 1`, `\x1b[{n}X` otherwise.
56const fn csi_optional_param_cost(n: u16) -> usize {
57    if n <= 1 {
58        CSI_LEN + 1
59    } else {
60        CSI_LEN + digit_count(n) + 1
61    }
62}
63
64/// Cost of a single-parameter CSI whose parameter is dropped when
65/// the 0-based input value is `0` (the canonical "absolute
66/// position" shape: CHA, HPA, VPA all default to row/col 1, which
67/// corresponds to a 0-based input of 0).
68///
69/// Shape: `\x1b[X` for `arg == 0`, `\x1b[{arg+1}X` otherwise.
70const fn csi_absolute_position_cost(arg: u16) -> usize {
71    if arg == 0 {
72        CSI_LEN + 1
73    } else {
74        CSI_LEN + digit_count(arg + 1) + 1
75    }
76}
77
78/// Cost of an erase-style CSI where the default parameter is `0`
79/// (the writer emits `ESC [ X` for `n == 0` and `ESC [ {n} X`
80/// otherwise).
81///
82/// Shape: `\x1b[X` for `n == 0`, `\x1b[{n}X` otherwise.
83const fn csi_erase_cost(n: u16) -> usize {
84    if n == 0 {
85        CSI_LEN + 1
86    } else {
87        CSI_LEN + digit_count(n) + 1
88    }
89}
90
91// ---------- Cursor movement -------------------------------------------------
92
93/// Cost of a CUP sequence for the given 0-based position. The writer
94/// drops the column when it is `0`, and drops both parameters when
95/// the destination is the origin.
96pub const fn cup_cost(row: u16, col: u16) -> usize {
97    if row == 0 && col == 0 {
98        // \x1b[H
99        CSI_LEN + 1
100    } else if col == 0 {
101        // \x1b[{row+1}H
102        CSI_LEN + digit_count(row + 1) + 1
103    } else {
104        // \x1b[{row+1};{col+1}H
105        CSI_LEN + digit_count(row + 1) + 1 + digit_count(col + 1) + 1
106    }
107}
108
109/// Cost of CUU (`\x1b[{n?}A`).
110pub const fn cuu_cost(n: u16) -> usize {
111    csi_optional_param_cost(n)
112}
113
114/// Cost of CUD (`\x1b[{n?}B`).
115pub const fn cud_cost(n: u16) -> usize {
116    csi_optional_param_cost(n)
117}
118
119/// Cost of CUF (`\x1b[{n?}C`).
120pub const fn cuf_cost(n: u16) -> usize {
121    csi_optional_param_cost(n)
122}
123
124/// Cost of CUB (`\x1b[{n?}D`).
125pub const fn cub_cost(n: u16) -> usize {
126    csi_optional_param_cost(n)
127}
128
129/// Cost of CHA (`\x1b[{col+1?}G`). The writer drops the parameter
130/// when `col == 0`.
131pub const fn cha_cost(col: u16) -> usize {
132    csi_absolute_position_cost(col)
133}
134
135/// Cost of HPA (``\x1b[{col+1?}` ``). The writer drops the parameter
136/// when `col == 0`.
137pub const fn hpa_cost(col: u16) -> usize {
138    csi_absolute_position_cost(col)
139}
140
141/// Cost of VPA (`\x1b[{row+1?}d`). The writer drops the parameter
142/// when `row == 0`.
143pub const fn vpa_cost(row: u16) -> usize {
144    csi_absolute_position_cost(row)
145}
146
147/// Cost of CHT (`\x1b[{n?}I`).
148pub const fn cht_cost(n: u16) -> usize {
149    csi_optional_param_cost(n)
150}
151
152/// Cost of CBT (`\x1b[{n?}Z`).
153pub const fn cbt_cost(n: u16) -> usize {
154    csi_optional_param_cost(n)
155}
156
157/// Cost of Reverse Index (`\x1bM`).
158pub const RI_COST: usize = 2;
159
160// ---------- Cell operations -------------------------------------------------
161
162/// Cost of ICH (`\x1b[{n?}@`).
163pub const fn ich_cost(n: u16) -> usize {
164    csi_optional_param_cost(n)
165}
166
167/// Cost of DCH (`\x1b[{n?}P`).
168pub const fn dch_cost(n: u16) -> usize {
169    csi_optional_param_cost(n)
170}
171
172/// Cost of ECH (`\x1b[{n?}X`).
173pub const fn ech_cost(n: u16) -> usize {
174    csi_optional_param_cost(n)
175}
176
177/// Cost of REP (`\x1b[{n?}b`).
178pub const fn rep_cost(n: u16) -> usize {
179    csi_optional_param_cost(n)
180}
181
182// ---------- Line operations -------------------------------------------------
183
184/// Cost of IL (`\x1b[{n?}L`).
185pub const fn il_cost(n: u16) -> usize {
186    csi_optional_param_cost(n)
187}
188
189/// Cost of DL (`\x1b[{n?}M`).
190pub const fn dl_cost(n: u16) -> usize {
191    csi_optional_param_cost(n)
192}
193
194/// Cost of SU (`\x1b[{n?}S`).
195pub const fn su_cost(n: u16) -> usize {
196    csi_optional_param_cost(n)
197}
198
199/// Cost of SD (`\x1b[{n?}T`).
200pub const fn sd_cost(n: u16) -> usize {
201    csi_optional_param_cost(n)
202}
203
204// ---------- Erase -----------------------------------------------------------
205
206/// Cost of EL (`\x1b[{n?}K`). `n == 0` omits the parameter.
207pub const fn el_cost(n: u16) -> usize {
208    csi_erase_cost(n)
209}
210
211/// Cost of ED (`\x1b[{n?}J`). `n == 0` omits the parameter.
212pub const fn ed_cost(n: u16) -> usize {
213    csi_erase_cost(n)
214}
215
216// ---------- Scroll region ---------------------------------------------------
217
218/// Cost of DECSTBM (`\x1b[{top+1};{bottom+1}r`).
219pub const fn decstbm_cost(top: u16, bottom: u16) -> usize {
220    // CSI + d(top+1) + ';' + d(bottom+1) + 'r'
221    CSI_LEN + digit_count(top + 1) + 1 + digit_count(bottom + 1) + 1
222}
223
224/// Cost of resetting DECSTBM to the full screen (`\x1b[r`).
225pub const DECSTBM_RESET_COST: usize = 3;
226
227// ---------- C0 / fixed prefixes --------------------------------------------
228
229/// Cost of a carriage return (`\r`).
230pub const CR_COST: usize = 1;
231
232/// Cost of an absolute home jump (`\x1b[H`).
233pub const HOME_COST: usize = 3;
234
235/// Cost of `n` literal line-feed bytes.
236pub const fn lf_cost(n: u16) -> usize {
237    n as usize
238}
239
240/// Cost of `n` literal backspace bytes.
241pub const fn bs_cost(n: u16) -> usize {
242    n as usize
243}
244
245/// Cost of `n` literal tab bytes.
246pub const fn tab_cost(n: u16) -> usize {
247    n as usize
248}
249
250#[cfg(test)]
251mod tests {
252    use super::*;
253
254    use crate::ansi::cursor::{
255        write_backtab, write_cha, write_cht, write_cub, write_cud, write_cuf, write_cup, write_cuu,
256        write_hpa, write_reverse_index, write_vpa,
257    };
258    use crate::ansi::screen::{
259        write_dch, write_delete_lines, write_ech, write_ed, write_el, write_ich,
260        write_insert_lines, write_rep, write_reset_scroll_region, write_scroll_down,
261        write_scroll_region, write_scroll_up,
262    };
263
264    /// Representative values exercising every branch of `digit_count`:
265    /// the `n == 0` / `n == 1` shortcuts, and 1..5 digit widths.
266    const NS: &[u16] = &[0, 1, 2, 9, 10, 99, 100, 999, 1000, 9999, 10000, u16::MAX];
267
268    fn write_to_vec(f: impl FnOnce(&mut Vec<u8>)) -> Vec<u8> {
269        let mut v = Vec::new();
270        f(&mut v);
271        v
272    }
273
274    #[test]
275    fn digit_count_matches_decimal_width() {
276        for &n in NS {
277            assert_eq!(digit_count(n), n.to_string().len(), "digit_count({n})");
278        }
279    }
280
281    #[test]
282    fn cup_cost_round_trips() {
283        let coords = [
284            (0, 0),
285            (0, 5),
286            (5, 0),
287            (5, 7),
288            (99, 99),
289            (999, 9),
290            (10, 1000),
291        ];
292        for (r, c) in coords {
293            let bytes = write_to_vec(|v| write_cup(v, r, c).unwrap());
294            assert_eq!(
295                cup_cost(r, c),
296                bytes.len(),
297                "cup_cost({r},{c}) vs {bytes:?}"
298            );
299        }
300    }
301
302    /// Drive the optional-param shape through every parameterized
303    /// writer that consumes it. Each call asserts that the cost
304    /// helper agrees with the writer's actual output.
305    #[test]
306    fn optional_param_costs_round_trip() {
307        for &n in NS {
308            // `write_cuu` and friends are no-ops for `n == 0`; that
309            // is the writer's own contract and we don't predict a
310            // cost for the empty emission.
311            if n == 0 {
312                continue;
313            }
314
315            let pairs: &[(&str, usize, Vec<u8>)] = &[
316                (
317                    "cuu",
318                    cuu_cost(n),
319                    write_to_vec(|v| write_cuu(v, n).unwrap()),
320                ),
321                (
322                    "cud",
323                    cud_cost(n),
324                    write_to_vec(|v| write_cud(v, n).unwrap()),
325                ),
326                (
327                    "cuf",
328                    cuf_cost(n),
329                    write_to_vec(|v| write_cuf(v, n).unwrap()),
330                ),
331                (
332                    "cub",
333                    cub_cost(n),
334                    write_to_vec(|v| write_cub(v, n).unwrap()),
335                ),
336                (
337                    "cht",
338                    cht_cost(n),
339                    write_to_vec(|v| write_cht(v, n).unwrap()),
340                ),
341                (
342                    "cbt",
343                    cbt_cost(n),
344                    write_to_vec(|v| write_backtab(v, n).unwrap()),
345                ),
346                (
347                    "ich",
348                    ich_cost(n),
349                    write_to_vec(|v| write_ich(v, n).unwrap()),
350                ),
351                (
352                    "dch",
353                    dch_cost(n),
354                    write_to_vec(|v| write_dch(v, n).unwrap()),
355                ),
356                (
357                    "ech",
358                    ech_cost(n),
359                    write_to_vec(|v| write_ech(v, n).unwrap()),
360                ),
361                (
362                    "rep",
363                    rep_cost(n),
364                    write_to_vec(|v| write_rep(v, n).unwrap()),
365                ),
366                (
367                    "il",
368                    il_cost(n),
369                    write_to_vec(|v| write_insert_lines(v, n).unwrap()),
370                ),
371                (
372                    "dl",
373                    dl_cost(n),
374                    write_to_vec(|v| write_delete_lines(v, n).unwrap()),
375                ),
376                (
377                    "su",
378                    su_cost(n),
379                    write_to_vec(|v| write_scroll_up(v, n).unwrap()),
380                ),
381                (
382                    "sd",
383                    sd_cost(n),
384                    write_to_vec(|v| write_scroll_down(v, n).unwrap()),
385                ),
386            ];
387            for (label, cost, bytes) in pairs {
388                assert_eq!(*cost, bytes.len(), "{label}({n}) bytes={bytes:?}");
389            }
390        }
391    }
392
393    #[test]
394    fn required_param_costs_round_trip() {
395        // u16::MAX overflows the writers' `arg + 1`; cap at 9999 (5
396        // digits exercise the wide branch). The `digit_count` test
397        // above already covers u16::MAX.
398        for &col in NS.iter().filter(|&&n| n <= 9999) {
399            let cha = write_to_vec(|v| write_cha(v, col).unwrap());
400            assert_eq!(cha_cost(col), cha.len(), "cha_cost({col})");
401            let hpa = write_to_vec(|v| write_hpa(v, col).unwrap());
402            assert_eq!(hpa_cost(col), hpa.len(), "hpa_cost({col})");
403            let vpa = write_to_vec(|v| write_vpa(v, col).unwrap());
404            assert_eq!(vpa_cost(col), vpa.len(), "vpa_cost({col})");
405        }
406    }
407
408    #[test]
409    fn erase_costs_round_trip() {
410        for n in 0u16..=3 {
411            let el = write_to_vec(|v| write_el(v, n).unwrap());
412            assert_eq!(el_cost(n), el.len(), "el_cost({n})");
413            let ed = write_to_vec(|v| write_ed(v, n).unwrap());
414            assert_eq!(ed_cost(n), ed.len(), "ed_cost({n})");
415        }
416    }
417
418    #[test]
419    fn decstbm_cost_round_trips() {
420        let cases = [(0u16, 0u16), (0, 23), (4, 19), (99, 199), (999, 9999)];
421        for (top, bottom) in cases {
422            let bytes = write_to_vec(|v| write_scroll_region(v, top, bottom).unwrap());
423            assert_eq!(
424                decstbm_cost(top, bottom),
425                bytes.len(),
426                "decstbm({top},{bottom})"
427            );
428        }
429    }
430
431    #[test]
432    fn decstbm_reset_cost_matches_writer() {
433        let bytes = write_to_vec(|v| write_reset_scroll_region(v).unwrap());
434        assert_eq!(DECSTBM_RESET_COST, bytes.len());
435    }
436
437    #[test]
438    fn ri_cost_matches_writer() {
439        let bytes = write_to_vec(|v| write_reverse_index(v).unwrap());
440        assert_eq!(RI_COST, bytes.len());
441    }
442}