From dbb0bd565ed469c08d03e544e022e9a7f6cd6f03 Mon Sep 17 00:00:00 2001 From: Mark Thomas Date: Tue, 25 Jun 2019 08:47:29 +0100 Subject: [PATCH] add parse_first_as_vec Add a convenience function to the escape parser that, like `parse_first`, matches only the first escape sequence, but instead collects all matching actions. --- termwiz/src/escape/parser/mod.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/termwiz/src/escape/parser/mod.rs b/termwiz/src/escape/parser/mod.rs index 0c35c13c7..8b1068bbb 100644 --- a/termwiz/src/escape/parser/mod.rs +++ b/termwiz/src/escape/parser/mod.rs @@ -80,6 +80,26 @@ impl Parser { self.parse(bytes, |action| result.push(action)); result } + + /// Similar to `parse_first` but collects all actions from the first sequence. + pub fn parse_first_as_vec(&mut self, bytes: &[u8]) -> Option<(Vec, usize)> { + let mut actions = Vec::new(); + let mut first_idx = None; + for (idx, b) in bytes.iter().enumerate() { + self.state_machine.advance( + &mut Performer { + callback: &mut |action| actions.push(action), + }, + *b, + ); + if !actions.is_empty() { + // if we recognized any actions, record the iterator index + first_idx = Some(idx); + break; + } + } + first_idx.map(|idx| (actions, idx + 1)) + } } struct Performer<'a, F: FnMut(Action) + 'a> {