Skip to main content

serialplugin_core/exchange/
completion.rs

1//! Detect when an in-flight exchange response is complete.
2
3use crate::at::parse::{AtCompletion, ExchangeMatch};
4use crate::events::ExchangeCompletionMode;
5use crate::exchange::options::{default_terminators, matches_terminators, ResolvedExchangeOptions};
6
7/// Completion state of one exchange, fed chunk by chunk: each byte is looked at a
8/// bounded number of times, so a long reply costs linear time.
9#[derive(Debug)]
10pub(crate) enum Completion {
11    At(AtCompletion),
12    Substring {
13        terminators: Vec<Vec<u8>>,
14        longest: usize,
15    },
16}
17
18impl Completion {
19    pub(crate) fn new(options: &ResolvedExchangeOptions) -> Self {
20        match options.completion_mode {
21            ExchangeCompletionMode::AtFinalLine => {
22                Completion::At(AtCompletion::new(false, options.result_format))
23            }
24            ExchangeCompletionMode::AtIntermediate => {
25                Completion::At(AtCompletion::new(true, options.result_format))
26            }
27            ExchangeCompletionMode::Substring => Completion::Substring {
28                longest: options.terminators.iter().map(Vec::len).max().unwrap_or(0),
29                terminators: options.terminators.clone(),
30            },
31        }
32    }
33
34    /// `buf` is everything received so far; its last `new` bytes just arrived.
35    pub(crate) fn push(&mut self, buf: &[u8], new: usize) -> Option<ExchangeMatch> {
36        let new = new.min(buf.len());
37        match self {
38            Completion::At(c) => c.push(&buf[buf.len() - new..]),
39            Completion::Substring {
40                terminators,
41                longest,
42            } => {
43                // A terminator ending in the new bytes starts at most `longest - 1` before them.
44                let from = (buf.len() - new).saturating_sub(longest.saturating_sub(1));
45                matches_terminators(&buf[from..], terminators).then(|| ExchangeMatch::Substring {
46                    term: String::from_utf8_lossy(default_terminators()[0].as_slice()).into_owned(),
47                })
48            }
49        }
50    }
51}
52
53/// One-shot check over a whole buffer.
54#[cfg(test)]
55pub(crate) fn check_exchange_complete(
56    buf: &[u8],
57    options: &ResolvedExchangeOptions,
58) -> Option<ExchangeMatch> {
59    Completion::new(options).push(buf, buf.len())
60}
61
62#[cfg(test)]
63mod tests {
64    use super::*;
65    use crate::events::{AtResultFormat, RxPrepareMode};
66
67    fn options(mode: ExchangeCompletionMode, terminators: Vec<Vec<u8>>) -> ResolvedExchangeOptions {
68        ResolvedExchangeOptions {
69            timeout_ms: 1000,
70            max_bytes: 4096,
71            terminators,
72            idle_ms: None,
73            rx_prepare: RxPrepareMode::None,
74            drain_idle_ms: 50,
75            drain_max_ms: 200,
76            completion_mode: mode,
77            result_format: AtResultFormat::Verbose,
78            command: Some("AT".into()),
79            solicited_prefixes: vec![],
80        }
81    }
82
83    /// Feed `reply` one byte at a time, as a slow link delivers it.
84    fn byte_by_byte(c: &mut Completion, reply: &[u8]) -> Vec<Option<ExchangeMatch>> {
85        (1..=reply.len()).map(|n| c.push(&reply[..n], 1)).collect()
86    }
87
88    /// Each push looks at exactly the new bytes: the AT parser sees every byte once.
89    #[test]
90    fn at_completion_sees_each_new_byte() {
91        let mut c = Completion::new(&options(ExchangeCompletionMode::AtFinalLine, vec![]));
92        let seen = byte_by_byte(&mut c, b"AT\r\r\nOK\r\n");
93        assert!(
94            seen[..seen.len() - 1].iter().all(Option::is_none),
95            "{seen:?}"
96        );
97        assert!(
98            matches!(seen.last(), Some(Some(ExchangeMatch::Ok))),
99            "{seen:?}"
100        );
101    }
102
103    /// The substring window reaches back `longest - 1` bytes before the new ones: a
104    /// terminator ending in the new bytes is found, one wholly in old bytes is not
105    /// looked at again.
106    #[test]
107    fn substring_window_covers_a_terminator_ending_in_the_new_bytes() {
108        let opts = options(ExchangeCompletionMode::Substring, vec![b"OK\r\n".to_vec()]);
109        let mut c = Completion::new(&opts);
110        let seen = byte_by_byte(&mut c, b"OK\r\n");
111        assert!(seen[..3].iter().all(Option::is_none), "{seen:?}");
112        assert!(seen[3].is_some(), "{seen:?}");
113        let mut c = Completion::new(&opts);
114        assert!(c.push(b"OK\r\nzz", 2).is_none());
115        assert!(c.push(b"zzOK\r\n", 6).is_some());
116    }
117}