-
-
Notifications
You must be signed in to change notification settings - Fork 336
Expand file tree
/
Copy pathlib.rs
More file actions
1903 lines (1645 loc) · 61.5 KB
/
Copy pathlib.rs
File metadata and controls
1903 lines (1645 loc) · 61.5 KB
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Parser for implementing virtual terminal emulators
//!
//! [`Parser`] is implemented according to [Paul Williams' ANSI parser
//! state machine]. The state machine doesn't assign meaning to the parsed data
//! and is thus not itself sufficient for writing a terminal emulator. Instead,
//! it is expected that an implementation of [`Perform`] is provided which does
//! something useful with the parsed data. The [`Parser`] handles the book
//! keeping, and the [`Perform`] gets to simply handle actions.
//!
//! # Examples
//!
//! For an example of using the [`Parser`] please see the examples folder. The example included
//! there simply logs all the actions [`Perform`] does. One quick thing to see it in action is to
//! pipe `vim` into it
//!
//! ```sh
//! cargo build --release --example parselog
//! vim | target/release/examples/parselog
//! ```
//!
//! Just type `:q` to exit.
//!
//! # Differences from original state machine description
//!
//! * UTF-8 Support for Input
//! * OSC Strings can be terminated by 0x07
//! * Only supports 7-bit codes. Some 8-bit codes are still supported, but they no longer work in
//! all states.
//!
//! [`Parser`]: struct.Parser.html
//! [`Perform`]: trait.Perform.html
//! [Paul Williams' ANSI parser state machine]: https://vt100.net/emu/dec_ansi_parser
#![deny(clippy::all, clippy::if_not_else, clippy::enum_glob_use)]
#![cfg_attr(not(feature = "std"), no_std)]
use core::mem::MaybeUninit;
use core::str;
#[cfg(not(feature = "std"))]
use arrayvec::ArrayVec;
mod params;
pub use params::{Params, ParamsIter};
const MAX_INTERMEDIATES: usize = 2;
const MAX_OSC_PARAMS: usize = 16;
const MAX_OSC_RAW: usize = 1024;
/// Parser for raw _VTE_ protocol which delegates actions to a [`Perform`]
///
/// [`Perform`]: trait.Perform.html
///
/// Generic over the value for the size of the raw Operating System Command
/// buffer. Only used when the `std` feature is not enabled.
#[derive(Default)]
pub struct Parser<const OSC_RAW_BUF_SIZE: usize = MAX_OSC_RAW> {
state: State,
intermediates: [u8; MAX_INTERMEDIATES],
intermediate_idx: usize,
params: Params,
param: u16,
#[cfg(not(feature = "std"))]
osc_raw: ArrayVec<u8, OSC_RAW_BUF_SIZE>,
#[cfg(feature = "std")]
osc_raw: Vec<u8>,
osc_params: [(usize, usize); MAX_OSC_PARAMS],
osc_num_params: usize,
ignoring: bool,
partial_utf8: [u8; 4],
partial_utf8_len: usize,
}
impl Parser {
/// Create a new Parser
pub fn new() -> Parser {
Default::default()
}
}
impl<const OSC_RAW_BUF_SIZE: usize> Parser<OSC_RAW_BUF_SIZE> {
/// Create a new Parser with a custom size for the Operating System Command
/// buffer.
///
/// Call with a const-generic param on `Parser`, like:
///
/// ```rust
/// let mut p = copa::Parser::<64>::new_with_size();
/// ```
#[cfg(not(feature = "std"))]
pub fn new_with_size() -> Parser<OSC_RAW_BUF_SIZE> {
Default::default()
}
#[inline]
fn params(&self) -> &Params {
&self.params
}
#[inline]
fn intermediates(&self) -> &[u8] {
&self.intermediates[..self.intermediate_idx]
}
/// Advance the parser state.
///
/// Requires a [`Perform`] implementation to handle the triggered actions.
///
/// [`Perform`]: trait.Perform.html
#[inline]
pub fn advance<P: Perform>(&mut self, performer: &mut P, bytes: &[u8]) {
let mut i = 0;
// Handle partial codepoints from previous calls to `advance`.
if self.partial_utf8_len != 0 {
i += self.advance_partial_utf8(performer, bytes);
}
while i != bytes.len() {
match self.state {
State::Ground => i += self.advance_ground(performer, &bytes[i..]),
_ => {
// Inlining it results in worse codegen.
let byte = bytes[i];
self.change_state(performer, byte);
i += 1;
}
}
}
}
/// Partially advance the parser state.
///
/// This is equivalent to [`Self::advance`], but stops when
/// [`Perform::terminated`] is true after reading a byte.
///
/// Returns the number of bytes read before termination.
#[inline]
#[must_use = "Returned value should be used to processs the remaining bytes"]
pub fn advance_until_terminated<P: Perform>(
&mut self,
performer: &mut P,
bytes: &[u8],
) -> usize {
let mut i = 0;
// Handle partial codepoints from previous calls to `advance`.
if self.partial_utf8_len != 0 {
i += self.advance_partial_utf8(performer, bytes);
}
while i != bytes.len() && !performer.terminated() {
match self.state {
State::Ground => i += self.advance_ground(performer, &bytes[i..]),
_ => {
// Inlining it results in worse codegen.
let byte = bytes[i];
self.change_state(performer, byte);
i += 1;
}
}
}
i
}
#[inline(always)]
fn change_state<P: Perform>(&mut self, performer: &mut P, byte: u8) {
match self.state {
State::CsiEntry => self.advance_csi_entry(performer, byte),
State::CsiIgnore => self.advance_csi_ignore(performer, byte),
State::CsiIntermediate => self.advance_csi_intermediate(performer, byte),
State::CsiParam => self.advance_csi_param(performer, byte),
State::DcsEntry => self.advance_dcs_entry(performer, byte),
State::DcsIgnore => self.anywhere(performer, byte),
State::DcsIntermediate => self.advance_dcs_intermediate(performer, byte),
State::DcsParam => self.advance_dcs_param(performer, byte),
State::DcsPassthrough => self.advance_dcs_passthrough(performer, byte),
State::Escape => self.advance_esc(performer, byte),
State::EscapeIntermediate => self.advance_esc_intermediate(performer, byte),
State::OscString => self.advance_osc_string(performer, byte),
State::SosString => self.advance_opaque_string(SosDispatch(performer), byte),
State::ApcString => self.advance_opaque_string(ApcDispatch(performer), byte),
State::PmString => self.advance_opaque_string(PmDispatch(performer), byte),
State::Ground => unreachable!(),
}
}
#[inline(always)]
fn advance_csi_entry<P: Perform>(&mut self, performer: &mut P, byte: u8) {
match byte {
0x00..=0x17 | 0x19 | 0x1C..=0x1F => performer.execute(byte),
0x20..=0x2F => {
self.action_collect(byte);
self.state = State::CsiIntermediate
}
0x30..=0x39 => {
self.action_paramnext(byte);
self.state = State::CsiParam
}
0x3A => {
self.action_subparam();
self.state = State::CsiParam
}
0x3B => {
self.action_param();
self.state = State::CsiParam
}
0x3C..=0x3F => {
self.action_collect(byte);
self.state = State::CsiParam
}
0x40..=0x7E => self.action_csi_dispatch(performer, byte),
_ => self.anywhere(performer, byte),
}
}
#[inline(always)]
fn advance_csi_ignore<P: Perform>(&mut self, performer: &mut P, byte: u8) {
match byte {
0x00..=0x17 | 0x19 | 0x1C..=0x1F => performer.execute(byte),
0x20..=0x3F => (),
0x40..=0x7E => self.state = State::Ground,
0x7F => (),
_ => self.anywhere(performer, byte),
}
}
#[inline(always)]
fn advance_csi_intermediate<P: Perform>(&mut self, performer: &mut P, byte: u8) {
match byte {
0x00..=0x17 | 0x19 | 0x1C..=0x1F => performer.execute(byte),
0x20..=0x2F => self.action_collect(byte),
0x30..=0x3F => self.state = State::CsiIgnore,
0x40..=0x7E => self.action_csi_dispatch(performer, byte),
_ => self.anywhere(performer, byte),
}
}
#[inline(always)]
fn advance_csi_param<P: Perform>(&mut self, performer: &mut P, byte: u8) {
match byte {
0x00..=0x17 | 0x19 | 0x1C..=0x1F => performer.execute(byte),
0x20..=0x2F => {
self.action_collect(byte);
self.state = State::CsiIntermediate
}
0x30..=0x39 => self.action_paramnext(byte),
0x3A => self.action_subparam(),
0x3B => self.action_param(),
0x3C..=0x3F => self.state = State::CsiIgnore,
0x40..=0x7E => self.action_csi_dispatch(performer, byte),
0x7F => (),
_ => self.anywhere(performer, byte),
}
}
#[inline(always)]
fn advance_dcs_entry<P: Perform>(&mut self, performer: &mut P, byte: u8) {
match byte {
0x00..=0x17 | 0x19 | 0x1C..=0x1F => (),
0x20..=0x2F => {
self.action_collect(byte);
self.state = State::DcsIntermediate
}
0x30..=0x39 => {
self.action_paramnext(byte);
self.state = State::DcsParam
}
0x3A => {
self.action_subparam();
self.state = State::DcsParam
}
0x3B => {
self.action_param();
self.state = State::DcsParam
}
0x3C..=0x3F => {
self.action_collect(byte);
self.state = State::DcsParam
}
0x40..=0x7E => self.action_hook(performer, byte),
0x7F => (),
_ => self.anywhere(performer, byte),
}
}
#[inline(always)]
fn advance_dcs_intermediate<P: Perform>(&mut self, performer: &mut P, byte: u8) {
match byte {
0x00..=0x17 | 0x19 | 0x1C..=0x1F => (),
0x20..=0x2F => self.action_collect(byte),
0x30..=0x3F => self.state = State::DcsIgnore,
0x40..=0x7E => self.action_hook(performer, byte),
0x7F => (),
_ => self.anywhere(performer, byte),
}
}
#[inline(always)]
fn advance_dcs_param<P: Perform>(&mut self, performer: &mut P, byte: u8) {
match byte {
0x00..=0x17 | 0x19 | 0x1C..=0x1F => (),
0x20..=0x2F => {
self.action_collect(byte);
self.state = State::DcsIntermediate
}
0x30..=0x39 => self.action_paramnext(byte),
0x3A => self.action_subparam(),
0x3B => self.action_param(),
0x3C..=0x3F => self.state = State::DcsIgnore,
0x40..=0x7E => self.action_hook(performer, byte),
0x7F => (),
_ => self.anywhere(performer, byte),
}
}
#[inline(always)]
fn advance_dcs_passthrough<P: Perform>(&mut self, performer: &mut P, byte: u8) {
match byte {
0x00..=0x17 | 0x19 | 0x1C..=0x7E => performer.put(byte),
0x18 | 0x1A => {
performer.unhook();
performer.execute(byte);
self.state = State::Ground
}
0x1B => {
performer.unhook();
self.reset_params();
self.state = State::Escape
}
0x7F => (),
0x9C => {
performer.unhook();
self.state = State::Ground
}
_ => (),
}
}
#[inline(always)]
fn advance_esc<P: Perform>(&mut self, performer: &mut P, byte: u8) {
match byte {
0x00..=0x17 | 0x19 | 0x1C..=0x1F => performer.execute(byte),
0x20..=0x2F => {
self.action_collect(byte);
self.state = State::EscapeIntermediate
}
0x30..=0x4F => {
performer.esc_dispatch(self.intermediates(), self.ignoring, byte);
self.state = State::Ground
}
0x50 => {
self.reset_params();
self.state = State::DcsEntry
}
0x51..=0x57 => {
performer.esc_dispatch(self.intermediates(), self.ignoring, byte);
self.state = State::Ground
}
0x58 => {
performer.sos_start();
self.state = State::SosString
}
0x59..=0x5A => {
performer.esc_dispatch(self.intermediates(), self.ignoring, byte);
self.state = State::Ground
}
0x5B => {
self.reset_params();
self.state = State::CsiEntry
}
0x5C => {
performer.esc_dispatch(self.intermediates(), self.ignoring, byte);
self.state = State::Ground
}
0x5D => {
self.osc_raw.clear();
self.osc_num_params = 0;
self.state = State::OscString
}
0x5E => {
performer.pm_start();
self.state = State::PmString
}
0x5F => {
performer.apc_start();
self.state = State::ApcString
}
0x60..=0x7E => {
performer.esc_dispatch(self.intermediates(), self.ignoring, byte);
self.state = State::Ground
}
// Anywhere.
0x18 | 0x1A => {
performer.execute(byte);
self.state = State::Ground
}
0x1B => (),
_ => (),
}
}
#[inline(always)]
fn advance_esc_intermediate<P: Perform>(&mut self, performer: &mut P, byte: u8) {
match byte {
0x00..=0x17 | 0x19 | 0x1C..=0x1F => performer.execute(byte),
0x20..=0x2F => self.action_collect(byte),
0x30..=0x7E => {
performer.esc_dispatch(self.intermediates(), self.ignoring, byte);
self.state = State::Ground
}
0x7F => (),
_ => self.anywhere(performer, byte),
}
}
#[inline(always)]
fn advance_osc_string<P: Perform>(&mut self, performer: &mut P, byte: u8) {
match byte {
0x00..=0x06 | 0x08..=0x17 | 0x19 | 0x1C..=0x1F => (),
0x07 => {
self.osc_end(performer, byte);
self.state = State::Ground
}
0x18 | 0x1A => {
self.osc_end(performer, byte);
performer.execute(byte);
self.state = State::Ground
}
0x1B => {
self.osc_end(performer, byte);
self.reset_params();
self.state = State::Escape
}
0x3B => {
#[cfg(not(feature = "std"))]
{
if self.osc_raw.is_full() {
return;
}
}
self.action_osc_put_param()
}
_ => self.action_osc_put(byte),
}
}
#[inline(always)]
fn advance_opaque_string<D: OpaqueDispatch>(&mut self, mut dispatcher: D, byte: u8) {
match byte {
0x07 => {
dispatcher.opaque_end();
self.state = State::Ground
}
0x18 | 0x1A => {
dispatcher.opaque_end();
dispatcher.execute(byte);
self.state = State::Ground
}
0x1B => {
dispatcher.opaque_end();
self.state = State::Escape
}
0x20..=0xFF => dispatcher.opaque_put(byte),
// Ignore all other control bytes.
_ => (),
}
}
#[inline(always)]
fn anywhere<P: Perform>(&mut self, performer: &mut P, byte: u8) {
match byte {
0x18 | 0x1A => {
performer.execute(byte);
self.state = State::Ground
}
0x1B => {
self.reset_params();
self.state = State::Escape
}
_ => (),
}
}
#[inline]
fn action_csi_dispatch<P: Perform>(&mut self, performer: &mut P, byte: u8) {
if self.params.is_full() {
self.ignoring = true;
} else {
self.params.push(self.param);
}
performer.csi_dispatch(
self.params(),
self.intermediates(),
self.ignoring,
byte as char,
);
self.state = State::Ground
}
#[inline]
fn action_hook<P: Perform>(&mut self, performer: &mut P, byte: u8) {
if self.params.is_full() {
self.ignoring = true;
} else {
self.params.push(self.param);
}
performer.hook(
self.params(),
self.intermediates(),
self.ignoring,
byte as char,
);
self.state = State::DcsPassthrough;
}
#[inline]
fn action_collect(&mut self, byte: u8) {
if self.intermediate_idx == MAX_INTERMEDIATES {
self.ignoring = true;
} else {
self.intermediates[self.intermediate_idx] = byte;
self.intermediate_idx += 1;
}
}
/// Advance to the next subparameter.
#[inline]
fn action_subparam(&mut self) {
if self.params.is_full() {
self.ignoring = true;
} else {
self.params.extend(self.param);
self.param = 0;
}
}
/// Advance to the next parameter.
#[inline]
fn action_param(&mut self) {
if self.params.is_full() {
self.ignoring = true;
} else {
self.params.push(self.param);
self.param = 0;
}
}
/// Advance inside the parameter without terminating it.
#[inline]
fn action_paramnext(&mut self, byte: u8) {
if self.params.is_full() {
self.ignoring = true;
} else {
// Continue collecting bytes into param.
self.param = self.param.saturating_mul(10);
self.param = self.param.saturating_add((byte - b'0') as u16);
}
}
/// Add OSC param separator.
#[inline]
fn action_osc_put_param(&mut self) {
let idx = self.osc_raw.len();
let param_idx = self.osc_num_params;
match param_idx {
// First param is special - 0 to current byte index.
0 => self.osc_params[param_idx] = (0, idx),
// Only process up to MAX_OSC_PARAMS.
MAX_OSC_PARAMS => return,
// All other params depend on previous indexing.
_ => {
let prev = self.osc_params[param_idx - 1];
let begin = prev.1;
self.osc_params[param_idx] = (begin, idx);
}
}
self.osc_num_params += 1;
}
#[inline(always)]
fn action_osc_put(&mut self, byte: u8) {
#[cfg(not(feature = "std"))]
{
if self.osc_raw.is_full() {
return;
}
}
self.osc_raw.push(byte);
}
fn osc_end<P: Perform>(&mut self, performer: &mut P, byte: u8) {
self.action_osc_put_param();
self.osc_dispatch(performer, byte);
self.osc_raw.clear();
self.osc_num_params = 0;
}
/// Reset escape sequence parameters and intermediates.
#[inline]
fn reset_params(&mut self) {
self.intermediate_idx = 0;
self.ignoring = false;
self.param = 0;
self.params.clear();
}
/// Separate method for osc_dispatch that borrows self as read-only
///
/// The aliasing is needed here for multiple slices into self.osc_raw
#[inline]
fn osc_dispatch<P: Perform>(&self, performer: &mut P, byte: u8) {
let mut slices: [MaybeUninit<&[u8]>; MAX_OSC_PARAMS] =
unsafe { MaybeUninit::uninit().assume_init() };
for (i, slice) in slices.iter_mut().enumerate().take(self.osc_num_params) {
let indices = self.osc_params[i];
*slice = MaybeUninit::new(&self.osc_raw[indices.0..indices.1]);
}
unsafe {
let num_params = self.osc_num_params;
let params = &slices[..num_params] as *const [MaybeUninit<&[u8]>]
as *const [&[u8]];
performer.osc_dispatch(&*params, byte == 0x07);
}
}
/// Advance the parser state from ground.
///
/// The ground state is handled separately since it can only be left using
/// the escape character (`\x1b`). This allows more efficient parsing by
/// using SIMD search with [`memchr`].
#[inline]
fn advance_ground<P: Perform>(&mut self, performer: &mut P, bytes: &[u8]) -> usize {
// Find the next escape character.
let num_bytes = bytes.len();
let plain_chars = memchr::memchr(0x1B, bytes).unwrap_or(num_bytes);
// If the next character is ESC, just process it and short-circuit.
if plain_chars == 0 {
self.state = State::Escape;
self.reset_params();
return 1;
}
match simdutf8::basic::from_utf8(&bytes[..plain_chars]) {
Ok(parsed) => {
Self::ground_dispatch(performer, parsed);
let mut processed = plain_chars;
// If there's another character, it must be escape so process it directly.
if processed < num_bytes {
self.state = State::Escape;
self.reset_params();
processed += 1;
}
processed
}
// Handle invalid and partial utf8.
Err(_) => {
// Use simdutf8::compat::from_utf8 to get detailed error information
let compat_err =
simdutf8::compat::from_utf8(&bytes[..plain_chars]).unwrap_err();
// Dispatch all the valid bytes.
let valid_bytes = compat_err.valid_up_to();
let parsed = unsafe { str::from_utf8_unchecked(&bytes[..valid_bytes]) };
Self::ground_dispatch(performer, parsed);
match compat_err.error_len() {
Some(len) => {
// Execute C1 escapes or emit replacement character.
if len == 1 && bytes[valid_bytes] <= 0x9F {
performer.execute(bytes[valid_bytes]);
} else {
performer.print('�');
}
// Restart processing after the invalid bytes.
//
// While we could theoretically try to just re-parse
// `bytes[valid_bytes + len..plain_chars]`, it's easier
// to just skip it and invalid utf8 is pretty rare anyway.
valid_bytes + len
}
None => {
if plain_chars < num_bytes {
// Process bytes cut off by escape.
performer.print('�');
self.state = State::Escape;
self.reset_params();
plain_chars + 1
} else {
// Process bytes cut off by the buffer end.
let extra_bytes = num_bytes - valid_bytes;
let partial_len = self.partial_utf8_len + extra_bytes;
self.partial_utf8[self.partial_utf8_len..partial_len]
.copy_from_slice(
&bytes[valid_bytes..valid_bytes + extra_bytes],
);
self.partial_utf8_len = partial_len;
num_bytes
}
}
}
}
}
}
/// Advance the parser while processing a partial utf8 codepoint.
#[inline]
fn advance_partial_utf8<P: Perform>(
&mut self,
performer: &mut P,
bytes: &[u8],
) -> usize {
// Try to copy up to 3 more characters, to ensure the codepoint is complete.
let old_bytes = self.partial_utf8_len;
let to_copy = bytes.len().min(self.partial_utf8.len() - old_bytes);
self.partial_utf8[old_bytes..old_bytes + to_copy]
.copy_from_slice(&bytes[..to_copy]);
self.partial_utf8_len += to_copy;
// Parse the unicode character.
match simdutf8::basic::from_utf8(&self.partial_utf8[..self.partial_utf8_len]) {
// If the entire buffer is valid, use the first character and continue parsing.
Ok(parsed) => {
let c = unsafe { parsed.chars().next().unwrap_unchecked() };
performer.print(c);
self.partial_utf8_len = 0;
c.len_utf8() - old_bytes
}
Err(_) => {
// Use simdutf8::compat::from_utf8 to get detailed error information
let compat_err = simdutf8::compat::from_utf8(
&self.partial_utf8[..self.partial_utf8_len],
)
.unwrap_err();
let valid_bytes = compat_err.valid_up_to();
// If we have any valid bytes, that means we partially copied another
// utf8 character into `partial_utf8`. Since we only care about the
// first character, we just ignore the rest.
if valid_bytes > 0 {
let c = unsafe {
let parsed =
str::from_utf8_unchecked(&self.partial_utf8[..valid_bytes]);
parsed.chars().next().unwrap_unchecked()
};
performer.print(c);
self.partial_utf8_len = 0;
return valid_bytes - old_bytes;
}
match compat_err.error_len() {
// If the partial character was also invalid, emit the replacement
// character.
Some(invalid_len) => {
performer.print('�');
self.partial_utf8_len = 0;
invalid_len - old_bytes
}
// If the character still isn't complete, wait for more data.
None => to_copy,
}
}
}
}
/// Handle ground dispatch of print/execute for all characters in a string.
#[inline]
fn ground_dispatch<P: Perform>(performer: &mut P, text: &str) {
for c in text.chars() {
match c {
'\x00'..='\x1f' | '\u{80}'..='\u{9f}' => performer.execute(c as u8),
_ => performer.print(c),
}
}
}
}
#[derive(PartialEq, Eq, Debug, Default, Copy, Clone)]
enum State {
CsiEntry,
CsiIgnore,
CsiIntermediate,
CsiParam,
DcsEntry,
DcsIgnore,
DcsIntermediate,
DcsParam,
DcsPassthrough,
Escape,
EscapeIntermediate,
OscString,
SosString,
ApcString,
PmString,
#[default]
Ground,
}
/// Performs actions requested by the Parser
///
/// Actions in this case mean, for example, handling a CSI escape sequence
/// describing cursor movement, or simply printing characters to the screen.
///
/// The methods on this type correspond to actions described in
/// <http://vt100.net/emu/dec_ansi_parser>. I've done my best to describe them in
/// a useful way in my own words for completeness, but the site should be
/// referenced if something isn't clear. If the site disappears at some point in
/// the future, consider checking archive.org.
pub trait Perform {
/// Draw a character to the screen and update states.
fn print(&mut self, _c: char) {}
/// Execute a C0 or C1 control function.
fn execute(&mut self, _byte: u8) {}
/// Invoked when a final character arrives in first part of device control
/// string.
///
/// The control function should be determined from the private marker, final
/// character, and execute with a parameter list. A handler should be
/// selected for remaining characters in the string; the handler
/// function should subsequently be called by `put` for every character in
/// the control string.
///
/// The `ignore` flag indicates that more than two intermediates arrived and
/// subsequent characters were ignored.
fn hook(
&mut self,
_params: &Params,
_intermediates: &[u8],
_ignore: bool,
_action: char,
) {
}
/// Pass bytes as part of a device control string to the handle chosen in
/// `hook`. C0 controls will also be passed to the handler.
fn put(&mut self, _byte: u8) {}
/// Called when a device control string is terminated.
///
/// The previously selected handler should be notified that the DCS has
/// terminated.
fn unhook(&mut self) {}
/// Dispatch an operating system command.
fn osc_dispatch(&mut self, _params: &[&[u8]], _bell_terminated: bool) {}
/// A final character has arrived for a CSI sequence
///
/// The `ignore` flag indicates that either more than two intermediates
/// arrived or the number of parameters exceeded the maximum supported
/// length, and subsequent characters were ignored.
fn csi_dispatch(
&mut self,
_params: &Params,
_intermediates: &[u8],
_ignore: bool,
_action: char,
) {
}
/// The final character of an escape sequence has arrived.
///
/// The `ignore` flag indicates that more than two intermediates arrived and
/// subsequent characters were ignored.
fn esc_dispatch(&mut self, _intermediates: &[u8], _ignore: bool, _byte: u8) {}
/// Invoked when the beginning of a new SOS (Start of String) sequence is
/// encountered.
fn sos_start(&mut self) {}
/// Invoked for every valid byte (0x20-0xFF) in a SOS (Start of String)
/// sequence.
fn sos_put(&mut self, _byte: u8) {}
/// Invoked when the end of an SOS (Start of String) sequence is
/// encountered.
fn sos_end(&mut self) {}
/// Invoked when the beginning of a new PM (Privacy Message) sequence is
/// encountered.
fn pm_start(&mut self) {}
/// Invoked for every valid byte (0x20-0xFF) in a PM (Privacy Message)
/// sequence.
fn pm_put(&mut self, _byte: u8) {}
/// Invoked when the end of a PM (Privacy Message) sequence is encountered.
fn pm_end(&mut self) {}
/// Invoked when the beginning of a new APC (Application Program Command)
/// sequence is encountered.
fn apc_start(&mut self) {}
/// Invoked for every valid byte (0x20-0xFF) in an APC (Application Program
/// Command) sequence.
fn apc_put(&mut self, _byte: u8) {}
/// Invoked when the end of an APC (Application Program Command) sequence is
/// encountered.
fn apc_end(&mut self) {}
/// Whether the parser should terminate prematurely.
///
/// This can be used in conjunction with
/// [`Parser::advance_until_terminated`] to terminate the parser after
/// receiving certain escape sequences like synchronized updates.
///
/// This is checked after every parsed byte, so no expensive computation
/// should take place in this function.
#[inline(always)]
fn terminated(&self) -> bool {
false
}
}
/// This trait is used internally to provide a common implementation for Opaque
/// Sequences (SOS, APC, PM). Implementations of this trait will just forward
/// calls to the equivalent method on [Perform]. Implementations of this trait
/// are always inlined to avoid overhead.
trait OpaqueDispatch {
fn execute(&mut self, byte: u8);
fn opaque_put(&mut self, byte: u8);
fn opaque_end(&mut self);
}
struct SosDispatch<'a, P: Perform>(&'a mut P);
impl<P: Perform> OpaqueDispatch for SosDispatch<'_, P> {
#[inline(always)]
fn execute(&mut self, byte: u8) {
self.0.execute(byte);
}
#[inline(always)]
fn opaque_put(&mut self, byte: u8) {
self.0.sos_put(byte);
}
#[inline(always)]
fn opaque_end(&mut self) {
self.0.sos_end();
}
}
struct ApcDispatch<'a, P: Perform>(&'a mut P);
impl<P: Perform> OpaqueDispatch for ApcDispatch<'_, P> {
#[inline(always)]
fn execute(&mut self, byte: u8) {
self.0.execute(byte);
}
#[inline(always)]
fn opaque_put(&mut self, byte: u8) {
self.0.apc_put(byte);
}
#[inline(always)]
fn opaque_end(&mut self) {
self.0.apc_end();
}
}
struct PmDispatch<'a, P: Perform>(&'a mut P);
impl<P: Perform> OpaqueDispatch for PmDispatch<'_, P> {
#[inline(always)]
fn execute(&mut self, byte: u8) {
self.0.execute(byte);
}
#[inline(always)]
fn opaque_put(&mut self, byte: u8) {
self.0.pm_put(byte);
}
#[inline(always)]
fn opaque_end(&mut self) {
self.0.pm_end();
}
}