rust-expect 0.5.0

Next-generation Expect-style terminal automation library for Rust
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
//! Pattern matching engine for expect operations.
//!
//! This module provides the core matching engine that combines
//! patterns, buffers, and timeouts into a cohesive expect operation.

use std::sync::Arc;
use std::time::{Duration, Instant};

use super::buffer::RingBuffer;
use super::cache::RegexCache;
use super::pattern::{Pattern, PatternSet};
use crate::types::Match;

/// The pattern matching engine.
pub struct Matcher {
    /// The output buffer.
    buffer: RingBuffer,
    /// Regex cache for compiled patterns.
    cache: Arc<RegexCache>,
    /// Default timeout for expect operations.
    default_timeout: Duration,
    /// Search window size (for performance optimization).
    search_window: Option<usize>,
}

impl Matcher {
    /// Create a new matcher with the specified buffer size.
    #[must_use]
    pub fn new(buffer_size: usize) -> Self {
        Self {
            buffer: RingBuffer::new(buffer_size),
            cache: Arc::new(RegexCache::with_default_size()),
            default_timeout: Duration::from_secs(30),
            search_window: None,
        }
    }

    /// Create a new matcher with shared regex cache.
    #[must_use]
    pub fn with_cache(buffer_size: usize, cache: Arc<RegexCache>) -> Self {
        Self {
            buffer: RingBuffer::new(buffer_size),
            cache,
            default_timeout: Duration::from_secs(30),
            search_window: None,
        }
    }

    /// Set the default timeout.
    pub const fn set_default_timeout(&mut self, timeout: Duration) {
        self.default_timeout = timeout;
    }

    /// Set the search window size.
    ///
    /// When set, pattern matching will only search the last N bytes
    /// of the buffer, improving performance for large buffers.
    pub const fn set_search_window(&mut self, size: Option<usize>) {
        self.search_window = size;
    }

    /// Append data to the buffer.
    pub fn append(&mut self, data: &[u8]) {
        self.buffer.append(data);
    }

    /// Get the current buffer.
    #[must_use]
    pub const fn buffer(&self) -> &RingBuffer {
        &self.buffer
    }

    /// Get the current buffer contents as a string.
    #[must_use]
    pub fn buffer_str(&mut self) -> String {
        self.buffer.as_str_lossy()
    }

    /// Clear the buffer.
    pub fn clear(&mut self) {
        self.buffer.clear();
    }

    /// Try to match a single pattern against the buffer.
    #[must_use]
    pub fn try_match(&mut self, pattern: &Pattern) -> Option<MatchResult> {
        let text = self.get_search_text();

        match pattern {
            Pattern::Literal(s) => text.find(s).map(|pos| MatchResult {
                pattern_index: 0,
                start: self.adjust_position(pos),
                end: self.adjust_position(pos + s.len()),
                captures: Vec::new(),
            }),
            Pattern::Regex(compiled) => compiled.find(&text).map(|m| {
                let captures = compiled.captures(&text);
                MatchResult {
                    pattern_index: 0,
                    start: self.adjust_position(m.start()),
                    end: self.adjust_position(m.end()),
                    captures,
                }
            }),
            Pattern::Glob(glob) => {
                self.try_glob_match(glob, &text)
                    .map(|(start, end)| MatchResult {
                        pattern_index: 0,
                        start: self.adjust_position(start),
                        end: self.adjust_position(end),
                        captures: Vec::new(),
                    })
            }
            // `Bytes(n)` matches once at least `n` raw bytes are buffered, and
            // consumes the first `n` of them. It is resolved here (not in
            // `Pattern::matches`) because it depends on the raw buffer length
            // rather than the search text.
            Pattern::Bytes(n) => (self.buffer.len() >= *n).then_some(MatchResult {
                pattern_index: 0,
                start: 0,
                end: *n,
                captures: Vec::new(),
            }),
            Pattern::Eof | Pattern::Timeout(_) => None,
        }
    }

    /// Try to match any pattern from a set against the buffer.
    #[must_use]
    pub fn try_match_any(&mut self, patterns: &PatternSet) -> Option<MatchResult> {
        let text = self.get_search_text();
        let buffer_len = self.buffer.len();
        let mut best: Option<MatchResult> = None;

        for (idx, named) in patterns.iter().enumerate() {
            // `Bytes(n)` depends on the raw buffer length, so it is matched
            // directly here rather than via `Pattern::matches` (which only sees
            // the search text and always returns `None` for `Bytes`).
            let result = if let Pattern::Bytes(n) = &named.pattern {
                (buffer_len >= *n).then_some(MatchResult {
                    pattern_index: idx,
                    start: 0,
                    end: *n,
                    captures: Vec::new(),
                })
            } else {
                named.pattern.matches(&text).map(|pm| MatchResult {
                    pattern_index: idx,
                    start: self.adjust_position(pm.start),
                    end: self.adjust_position(pm.end),
                    captures: pm.captures,
                })
            };

            if let Some(result) = result {
                match &best {
                    None => best = Some(result),
                    Some(current) if result.start < current.start => best = Some(result),
                    _ => {}
                }
            }
        }

        best
    }

    /// Consume matched content from the buffer and return a Match.
    pub fn consume_match(&mut self, result: &MatchResult) -> Match {
        let before = self.buffer.consume_before(result.start);
        let matched_bytes = self.buffer.consume(result.end - result.start);
        let matched = String::from_utf8_lossy(&matched_bytes).into_owned();
        let after = self.buffer_str();

        Match::new(result.pattern_index, matched, before, after)
            .with_captures(result.captures.clone())
    }

    /// Get the timeout for a pattern set.
    #[must_use]
    pub fn get_timeout(&self, patterns: &PatternSet) -> Duration {
        patterns.min_timeout().unwrap_or(self.default_timeout)
    }

    /// Get the regex cache.
    #[must_use]
    pub const fn cache(&self) -> &Arc<RegexCache> {
        &self.cache
    }

    /// Get the text to search, applying search window if set.
    fn get_search_text(&mut self) -> String {
        match self.search_window {
            Some(window) => {
                let tail = self.buffer.tail(window);
                String::from_utf8_lossy(&tail).into_owned()
            }
            None => self.buffer.as_str_lossy(),
        }
    }

    /// Adjust position when using search window.
    fn adjust_position(&self, pos: usize) -> usize {
        match self.search_window {
            Some(window) => {
                let buffer_len = self.buffer.len();
                let offset = buffer_len.saturating_sub(window);
                offset + pos
            }
            None => pos,
        }
    }

    /// Simple glob matching.
    #[allow(clippy::unused_self)]
    fn try_glob_match(&self, pattern: &str, text: &str) -> Option<(usize, usize)> {
        // Convert glob to a simple search
        // For now, just handle * as prefix/suffix
        if let Some(rest) = pattern.strip_prefix('*') {
            if let Some(inner) = rest.strip_suffix('*') {
                // Pattern like *inner*
                text.find(inner).map(|pos| (pos, pos + inner.len()))
            } else {
                // Pattern like *suffix
                let suffix = rest;
                if text.ends_with(suffix) {
                    let start = text.len() - suffix.len();
                    Some((start, text.len()))
                } else {
                    None
                }
            }
        } else if let Some(prefix) = pattern.strip_suffix('*') {
            // Pattern like prefix*
            if text.starts_with(prefix) {
                Some((0, prefix.len()))
            } else {
                None
            }
        } else {
            text.find(pattern).map(|pos| (pos, pos + pattern.len()))
        }
    }
}

impl Default for Matcher {
    fn default() -> Self {
        Self::new(super::buffer::DEFAULT_CAPACITY)
    }
}

/// Result of a pattern match.
#[derive(Debug, Clone)]
pub struct MatchResult {
    /// Index of the pattern that matched.
    pub pattern_index: usize,
    /// Start position in the buffer.
    pub start: usize,
    /// End position in the buffer.
    pub end: usize,
    /// Capture groups.
    pub captures: Vec<String>,
}

impl MatchResult {
    /// Get the length of the match.
    #[must_use]
    pub const fn len(&self) -> usize {
        self.end - self.start
    }

    /// Check if the match is empty.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.start == self.end
    }
}

/// State machine for async expect operations.
pub struct ExpectState {
    /// The patterns being matched.
    patterns: PatternSet,
    /// Start time of the expect operation.
    start_time: Instant,
    /// Timeout duration.
    timeout: Duration,
    /// Whether EOF has been detected.
    eof_detected: bool,
}

impl ExpectState {
    /// Create a new expect state.
    #[must_use]
    pub fn new(patterns: PatternSet, timeout: Duration) -> Self {
        Self {
            patterns,
            start_time: Instant::now(),
            timeout,
            eof_detected: false,
        }
    }

    /// Check if the operation has timed out.
    #[must_use]
    pub fn is_timed_out(&self) -> bool {
        self.start_time.elapsed() >= self.timeout
    }

    /// Get the remaining time until timeout.
    #[must_use]
    pub fn remaining_time(&self) -> Duration {
        self.timeout.saturating_sub(self.start_time.elapsed())
    }

    /// Mark EOF as detected.
    pub const fn set_eof(&mut self) {
        self.eof_detected = true;
    }

    /// Check if EOF was detected.
    #[must_use]
    pub const fn is_eof(&self) -> bool {
        self.eof_detected
    }

    /// Get the patterns.
    #[must_use]
    pub const fn patterns(&self) -> &PatternSet {
        &self.patterns
    }

    /// Check if the patterns include an EOF pattern.
    #[must_use]
    pub fn expects_eof(&self) -> bool {
        self.patterns.has_eof()
    }
}

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

    #[test]
    fn matcher_literal() {
        let mut matcher = Matcher::new(1024);
        matcher.append(b"hello world");

        let pattern = Pattern::literal("world");
        let result = matcher.try_match(&pattern);
        assert!(result.is_some());

        let m = result.unwrap();
        assert_eq!(m.start, 6);
        assert_eq!(m.end, 11);
    }

    #[test]
    fn matcher_regex() {
        let mut matcher = Matcher::new(1024);
        matcher.append(b"value: 42");

        let pattern = Pattern::regex(r"\d+").unwrap();
        let result = matcher.try_match(&pattern);
        assert!(result.is_some());

        let m = result.unwrap();
        assert_eq!(m.start, 7);
        assert_eq!(m.end, 9);
    }

    #[test]
    fn matcher_consume() {
        let mut matcher = Matcher::new(1024);
        matcher.append(b"prefix|match|suffix");

        let pattern = Pattern::literal("match");
        let result = matcher.try_match(&pattern).unwrap();
        let m = matcher.consume_match(&result);

        assert_eq!(m.before, "prefix|");
        assert_eq!(m.matched, "match");
        assert_eq!(m.after, "|suffix");
    }

    #[test]
    fn matcher_pattern_set() {
        let mut matcher = Matcher::new(1024);
        matcher.append(b"error: something went wrong");

        let mut patterns = PatternSet::new();
        patterns
            .add(Pattern::literal("success"))
            .add(Pattern::literal("error"));

        let result = matcher.try_match_any(&patterns);
        assert!(result.is_some());
        assert_eq!(result.unwrap().pattern_index, 1);
    }

    #[test]
    fn matcher_bytes_waits_then_matches() {
        let mut matcher = Matcher::new(1024);
        let pattern = Pattern::bytes(5);

        // Fewer than 5 bytes: no match.
        matcher.append(b"abc");
        assert!(
            matcher.try_match(&pattern).is_none(),
            "Bytes(5) must not match with only 3 bytes buffered"
        );

        // Reaching 5 bytes: matches, consuming exactly the first 5.
        matcher.append(b"defgh");
        let result = matcher.try_match(&pattern).expect("Bytes(5) should match");
        assert_eq!(result.start, 0);
        assert_eq!(result.end, 5);

        let m = matcher.consume_match(&result);
        assert_eq!(m.matched, "abcde");
    }

    #[test]
    fn matcher_bytes_in_pattern_set() {
        let mut matcher = Matcher::new(1024);
        matcher.append(b"abcdef");

        let mut patterns = PatternSet::new();
        patterns.add(Pattern::literal("zzz")).add(Pattern::bytes(4));

        let result = matcher
            .try_match_any(&patterns)
            .expect("Bytes(4) should match in the set");
        assert_eq!(result.pattern_index, 1);
        assert_eq!(result.end - result.start, 4);
    }

    #[test]
    fn expect_state_timeout() {
        let patterns = PatternSet::from_patterns(vec![Pattern::literal("test")]);
        let state = ExpectState::new(patterns, Duration::from_millis(10));

        assert!(!state.is_timed_out());
        std::thread::sleep(Duration::from_millis(20));
        assert!(state.is_timed_out());
    }
}