File: parse.rs

package info (click to toggle)
rustc 1.85.0%2Bdfsg3-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental, sid, trixie
  • size: 893,396 kB
  • sloc: xml: 158,127; python: 35,830; javascript: 19,497; cpp: 19,002; sh: 17,245; ansic: 13,127; asm: 4,376; makefile: 1,051; perl: 29; lisp: 29; ruby: 19; sql: 11
file content (207 lines) | stat: -rw-r--r-- 5,642 bytes parent folder | download | duplicates (4)
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
#![allow(clippy::incompatible_msrv)] // not verifying benches atm

use std::hint::black_box;

use anstyle_parse::DefaultCharAccumulator;
use anstyle_parse::Params;
use anstyle_parse::Parser;
use anstyle_parse::Perform;

#[divan::bench(args = DATA)]
fn advance(data: &Data) {
    let mut dispatcher = BenchDispatcher;
    let mut parser = Parser::<DefaultCharAccumulator>::new();

    for byte in data.content() {
        parser.advance(&mut dispatcher, *byte);
    }
}

#[divan::bench(args = DATA)]
fn advance_strip(data: &Data) -> String {
    let mut stripped = Strip::with_capacity(data.content().len());
    let mut parser = Parser::<DefaultCharAccumulator>::new();

    for byte in data.content() {
        parser.advance(&mut stripped, *byte);
    }

    black_box(stripped.0)
}

#[divan::bench(args = DATA)]
fn state_change(data: &Data) {
    let mut state = anstyle_parse::state::State::default();
    for byte in data.content() {
        let (next_state, action) = anstyle_parse::state::state_change(state, *byte);
        state = next_state;
        black_box(action);
    }
}

#[divan::bench(args = DATA)]
fn state_change_strip_str(bencher: divan::Bencher<'_, '_>, data: &Data) {
    if let Ok(content) = std::str::from_utf8(data.content()) {
        bencher
            .with_inputs(|| content)
            .bench_local_values(|content| {
                let stripped = strip_str(content);

                black_box(stripped)
            });
    }
}

struct BenchDispatcher;
impl Perform for BenchDispatcher {
    fn print(&mut self, c: char) {
        black_box(c);
    }

    fn execute(&mut self, byte: u8) {
        black_box(byte);
    }

    fn hook(&mut self, params: &Params, intermediates: &[u8], ignore: bool, c: u8) {
        black_box((params, intermediates, ignore, c));
    }

    fn put(&mut self, byte: u8) {
        black_box(byte);
    }

    fn osc_dispatch(&mut self, params: &[&[u8]], bell_terminated: bool) {
        black_box((params, bell_terminated));
    }

    fn csi_dispatch(&mut self, params: &Params, intermediates: &[u8], ignore: bool, c: u8) {
        black_box((params, intermediates, ignore, c));
    }

    fn esc_dispatch(&mut self, intermediates: &[u8], ignore: bool, byte: u8) {
        black_box((intermediates, ignore, byte));
    }
}

#[derive(Default)]
struct Strip(String);
impl Strip {
    fn with_capacity(capacity: usize) -> Self {
        Self(String::with_capacity(capacity))
    }
}
impl Perform for Strip {
    fn print(&mut self, c: char) {
        self.0.push(c);
    }

    fn execute(&mut self, byte: u8) {
        if byte.is_ascii_whitespace() {
            self.0.push(byte as char);
        }
    }
}

fn strip_str(content: &str) -> String {
    use anstyle_parse::state::state_change;
    use anstyle_parse::state::Action;
    use anstyle_parse::state::State;

    #[inline]
    fn is_utf8_continuation(b: u8) -> bool {
        matches!(b, 0x80..=0xbf)
    }

    #[inline]
    fn is_printable(action: Action, byte: u8) -> bool {
        action == Action::Print
                    || action == Action::BeginUtf8
                    // since we know the input is valid UTF-8, the only thing  we can do with
                    // continuations is to print them
                    || is_utf8_continuation(byte)
                    || (action == Action::Execute && byte.is_ascii_whitespace())
    }

    let mut stripped = Vec::with_capacity(content.len());

    let mut bytes = content.as_bytes();
    while !bytes.is_empty() {
        let offset = bytes.iter().copied().position(|b| {
            let (_next_state, action) = state_change(State::Ground, b);
            !is_printable(action, b)
        });
        let (printable, next) = bytes.split_at(offset.unwrap_or(bytes.len()));
        stripped.extend(printable);
        bytes = next;

        let mut state = State::Ground;
        let offset = bytes.iter().copied().position(|b| {
            let (next_state, action) = state_change(state, b);
            if next_state != State::Anywhere {
                state = next_state;
            }
            is_printable(action, b)
        });
        let (_, next) = bytes.split_at(offset.unwrap_or(bytes.len()));
        bytes = next;
    }

    #[allow(clippy::unwrap_used)]
    String::from_utf8(stripped).unwrap()
}

const DATA: &[Data] = &[
    Data(
        "0-state_changes",
        b"\x1b]2;X\x1b\\ \x1b[0m \x1bP0@\x1b\\".as_slice(),
    ),
    #[cfg(feature = "utf8")]
    Data("1-demo.vte", include_bytes!("../tests/demo.vte").as_slice()),
    Data(
        "2-rg_help.vte",
        include_bytes!("../tests/rg_help.vte").as_slice(),
    ),
    Data(
        "3-rg_linus.vte",
        include_bytes!("../tests/rg_linus.vte").as_slice(),
    ),
];

#[derive(Debug)]
struct Data(&'static str, &'static [u8]);

impl Data {
    const fn name(&self) -> &'static str {
        self.0
    }

    const fn content(&self) -> &'static [u8] {
        self.1
    }
}

impl std::fmt::Display for Data {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.name().fmt(f)
    }
}

#[test]
fn verify_data() {
    for data in DATA {
        let Data(name, content) = data;
        // Make sure the comparison is fair
        if let Ok(content) = std::str::from_utf8(content) {
            let mut stripped = Strip::with_capacity(content.len());
            let mut parser = Parser::<DefaultCharAccumulator>::new();
            for byte in content.as_bytes() {
                parser.advance(&mut stripped, *byte);
            }
            assert_eq!(stripped.0, strip_str(content));
        }
    }
}

fn main() {
    divan::main();
}