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}