use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use crate::codec;
use crate::util::find_subsequence;
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct MatchRequest {
pub pattern: String,
#[serde(default)]
pub config: MatchConfig,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct MatchConfig {
#[serde(default = "default_match_mode")]
pub mode: MatchMode,
#[serde(default = "default_pattern_encoding")]
pub pattern_encoding: PatternEncoding,
#[serde(default)]
#[schemars(schema_with = "crate::schema_helpers::option_uint_schema")]
pub context_amount_of_matched_bytes: Option<usize>,
}
impl Default for MatchConfig {
fn default() -> Self {
Self {
mode: default_match_mode(),
pattern_encoding: default_pattern_encoding(),
context_amount_of_matched_bytes: None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum MatchMode {
LiteralSubstring,
Regex,
Glob,
}
fn default_match_mode() -> MatchMode {
MatchMode::LiteralSubstring
}
impl std::fmt::Display for MatchMode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
MatchMode::LiteralSubstring => f.write_str("literal_substring"),
MatchMode::Regex => f.write_str("regex"),
MatchMode::Glob => f.write_str("glob"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum PatternEncoding {
Utf8,
Hex,
#[serde(rename = "base64")]
Base64,
}
fn default_pattern_encoding() -> PatternEncoding {
PatternEncoding::Utf8
}
impl std::fmt::Display for PatternEncoding {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
PatternEncoding::Utf8 => f.write_str("utf8"),
PatternEncoding::Hex => f.write_str("hex"),
PatternEncoding::Base64 => f.write_str("base64"),
}
}
}
impl From<PatternEncoding> for codec::Encoding {
fn from(pe: PatternEncoding) -> Self {
match pe {
PatternEncoding::Utf8 => codec::Encoding::Utf8,
PatternEncoding::Hex => codec::Encoding::Hex,
PatternEncoding::Base64 => codec::Encoding::Base64,
}
}
}
pub(crate) const REGEX_GLOB_OVERLAP_ALLOWANCE: usize = 256;
#[doc(hidden)]
#[derive(Debug, Clone)]
pub struct SavedMatchContext {
global_index: usize,
payload: ShapedMatchPayload,
}
#[derive(Debug)]
pub enum Matcher {
Literal {
needle: Vec<u8>,
window: Vec<u8>,
context_amount: Option<usize>,
base: usize,
last_match_context: Option<SavedMatchContext>,
},
Regex {
re: regex::bytes::Regex,
window: Vec<u8>,
context_amount: Option<usize>,
base: usize,
},
Glob {
pat: glob::Pattern,
window: Vec<u8>,
context_amount: Option<usize>,
base: usize,
first_line_partial: bool,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MatchResult {
NoMatch,
Found(usize),
}
impl Matcher {
pub fn new_literal(needle: Vec<u8>) -> Option<Self> {
if needle.is_empty() {
return None;
}
Some(Self::Literal {
needle,
window: Vec::new(),
context_amount: None,
base: 0,
last_match_context: None,
})
}
pub fn with_context(self, context_amount: Option<usize>) -> Self {
match self {
Self::Literal {
needle,
window,
base,
last_match_context,
..
} => Self::Literal {
needle,
window,
context_amount,
base,
last_match_context,
},
Self::Regex {
re, window, base, ..
} => Self::Regex {
re,
window,
context_amount,
base,
},
Self::Glob {
pat,
window,
base,
first_line_partial,
..
} => Self::Glob {
pat,
window,
context_amount,
base,
first_line_partial,
},
}
}
pub fn context_amount(&self) -> Option<usize> {
match self {
Self::Literal { context_amount, .. }
| Self::Regex { context_amount, .. }
| Self::Glob { context_amount, .. } => *context_amount,
}
}
pub fn needle_len(&self) -> Option<usize> {
match self {
Self::Literal { needle, .. } => Some(needle.len()),
_ => None,
}
}
pub fn check(&self) -> MatchResult {
match self {
Self::Literal {
needle,
window,
base,
..
} => find_subsequence(window, needle)
.map_or(MatchResult::NoMatch, |i| MatchResult::Found(base + i)),
Self::Regex {
re, window, base, ..
} => re.find(window).map_or(MatchResult::NoMatch, |m| {
MatchResult::Found(base + m.start())
}),
Self::Glob {
pat,
window,
base,
first_line_partial,
..
} => {
let decoded = String::from_utf8_lossy(window);
let mut byte_offset: usize = 0;
let mut first_line = true;
for line in decoded.split('\n') {
let line_content = line.strip_suffix('\r').unwrap_or(line);
let skip = first_line && *first_line_partial;
first_line = false;
if !skip && pat.matches(line_content) {
return MatchResult::Found(base + byte_offset);
}
byte_offset += line.len() + 1; }
MatchResult::NoMatch
}
}
}
pub fn push(&mut self, chunk: &[u8]) -> MatchResult {
if let Self::Literal {
last_match_context, ..
} = self
{
*last_match_context = None;
}
match self {
Self::Literal { window, .. }
| Self::Regex { window, .. }
| Self::Glob { window, .. } => {
window.extend_from_slice(chunk);
}
}
let result = self.check();
if let MatchResult::Found(global_index) = result {
self.save_literal_context(global_index, None);
}
result
}
pub fn retained_window_limit(&self, max_buffered_bytes: usize) -> usize {
let allowance = match self {
Self::Literal { needle, .. } => needle.len().saturating_sub(1),
Self::Regex { .. } | Self::Glob { .. } => REGEX_GLOB_OVERLAP_ALLOWANCE,
};
max_buffered_bytes.saturating_add(allowance)
}
fn save_literal_context(&mut self, global_index: usize, context_cap: Option<usize>) {
if let Self::Literal {
needle,
window,
context_amount: Some(context),
base,
last_match_context,
..
} = self
{
let effective_context = context_cap.map_or(*context, |cap| (*context).min(cap));
let local = global_index.saturating_sub(*base);
let pre_start = local.saturating_sub(effective_context);
let match_end = local.saturating_add(needle.len()).min(window.len());
let payload = ShapedMatchPayload {
data: window[pre_start..match_end].to_vec(),
match_index: local - pre_start,
needle_len: needle.len(),
};
*last_match_context = Some(SavedMatchContext {
global_index,
payload,
});
}
}
pub fn push_bounded(&mut self, chunk: &[u8], max_buffered_bytes: usize) -> MatchResult {
let result = self.push(chunk);
if let MatchResult::Found(global_index) = result {
self.save_literal_context(global_index, Some(max_buffered_bytes));
}
let limit = self.retained_window_limit(max_buffered_bytes);
if self.len() > limit {
self.truncate_front(limit);
}
result
}
#[cfg_attr(mutants, mutants::skip)]
pub fn truncate_front(&mut self, keep: usize) {
match self {
Self::Literal { window, base, .. } | Self::Regex { window, base, .. } => {
let drop = window.len().saturating_sub(keep);
if drop > 0 {
window.drain(..drop);
*base += drop;
}
}
Self::Glob {
window,
base,
first_line_partial,
..
} => {
let drop = window.len().saturating_sub(keep);
if drop > 0 {
*first_line_partial = window[drop - 1] != b'\n';
window.drain(..drop);
*base += drop;
}
}
}
}
pub fn len(&self) -> usize {
match self {
Self::Literal { window, .. }
| Self::Regex { window, .. }
| Self::Glob { window, .. } => window.len(),
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn reset_window(&mut self) {
match self {
Self::Literal {
window,
base,
last_match_context,
..
} => {
window.clear();
*base = 0;
*last_match_context = None;
}
Self::Regex { window, base, .. } => {
window.clear();
*base = 0;
}
Self::Glob {
window,
base,
first_line_partial,
..
} => {
window.clear();
*base = 0;
*first_line_partial = false;
}
}
}
pub fn shape_literal_match_context(
&self,
global_match_index: usize,
) -> Option<ShapedMatchPayload> {
match self {
Self::Literal {
context_amount,
last_match_context,
..
} => {
if context_amount.is_none() {
return None;
}
match last_match_context {
Some(ctx) if ctx.global_index == global_match_index => {
Some(ctx.payload.clone())
}
_ => None,
}
}
Self::Regex { .. } | Self::Glob { .. } => None,
}
}
}
pub fn validate_match_request(req: &MatchRequest) -> Result<Matcher, String> {
let encoding: codec::Encoding = req.config.pattern_encoding.into();
let decoded = codec::decode(encoding, &req.pattern)
.map_err(|e| format!("Pattern decoding failed - {e}"))?;
if decoded.is_empty() {
return Err("Pattern must not be empty after decoding".into());
}
let context = req.config.context_amount_of_matched_bytes;
match req.config.mode {
MatchMode::LiteralSubstring => Matcher::new_literal(decoded)
.map(|m| m.with_context(context))
.ok_or_else(|| "Pattern must not be empty after decoding".into()),
MatchMode::Regex => {
let re = regex::bytes::Regex::new(&String::from_utf8_lossy(&decoded))
.map_err(|e| format!("Invalid regex pattern: {e}"))?;
Ok(Matcher::Regex {
re,
window: Vec::new(),
context_amount: context,
base: 0,
})
}
MatchMode::Glob => {
let pat = glob::Pattern::new(&String::from_utf8_lossy(&decoded))
.map_err(|e| format!("Invalid glob pattern: {e}"))?;
Ok(Matcher::Glob {
pat,
window: Vec::new(),
context_amount: context,
base: 0,
first_line_partial: false,
})
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ShapedMatchPayload {
pub data: Vec<u8>,
pub match_index: usize,
pub needle_len: usize,
}
pub fn shape_match_context(
accumulated: &[u8],
match_index: usize,
needle_len: usize,
context_amount: Option<usize>,
) -> ShapedMatchPayload {
let Some(n) = context_amount else {
return ShapedMatchPayload {
data: accumulated.to_vec(),
match_index,
needle_len,
};
};
let pre_start = match_index.saturating_sub(n);
let match_end = match_index + needle_len;
let shaped = accumulated[pre_start..match_end].to_vec();
let new_match_index = match_index - pre_start;
ShapedMatchPayload {
data: shaped,
match_index: new_match_index,
needle_len,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn byte_matcher_finds_immediate_match() {
let mut m = Matcher::new_literal(b"OK>".to_vec()).unwrap();
assert_eq!(m.push(b"OK>"), MatchResult::Found(0));
}
#[test]
fn byte_matcher_finds_offset_match() {
let mut m = Matcher::new_literal(b"OK>".to_vec()).unwrap();
assert_eq!(m.push(b"hell"), MatchResult::NoMatch);
assert_eq!(m.push(b"O"), MatchResult::NoMatch);
assert_eq!(m.push(b"K>!"), MatchResult::Found(4));
}
#[test]
fn byte_matcher_rejects_empty_needle() {
assert!(Matcher::new_literal(Vec::new()).is_none());
}
#[test]
fn byte_matcher_truncate_front_works() {
let mut m = Matcher::new_literal(b"OK>".to_vec()).unwrap();
m.push(b"AAAABBB");
m.truncate_front(3);
assert_eq!(m.len(), 3);
assert_eq!(m.push(b"OK>"), MatchResult::Found(7));
}
#[test]
fn validate_match_request_literal_hex() {
let req = MatchRequest {
pattern: "4f4b3e".into(),
config: MatchConfig {
mode: MatchMode::LiteralSubstring,
pattern_encoding: PatternEncoding::Hex,
context_amount_of_matched_bytes: None,
},
};
let matcher = validate_match_request(&req).unwrap();
assert_eq!(matcher.needle_len(), Some(3)); }
#[test]
fn validate_match_request_empty_pattern_rejected() {
let req = MatchRequest {
pattern: "".into(),
config: MatchConfig::default(),
};
assert!(validate_match_request(&req).is_err());
}
#[test]
fn match_config_default_is_literal_utf8() {
let cfg = MatchConfig::default();
assert_eq!(cfg.mode, MatchMode::LiteralSubstring);
assert_eq!(cfg.pattern_encoding, PatternEncoding::Utf8);
}
#[test]
fn pattern_encoding_display_roundtrips() {
assert_eq!(PatternEncoding::Utf8.to_string(), "utf8");
assert_eq!(PatternEncoding::Hex.to_string(), "hex");
assert_eq!(PatternEncoding::Base64.to_string(), "base64");
}
#[test]
fn byte_matcher_no_match_returns_no_match() {
let mut m = Matcher::new_literal(b"XYZ".to_vec()).unwrap();
assert_eq!(m.push(b"ABCDEF"), MatchResult::NoMatch);
assert_eq!(m.check(), MatchResult::NoMatch);
}
#[test]
fn shape_context_returns_pre_match_bytes_plus_matched() {
let accumulated = b"prefix___OK>suffix".to_vec();
let shaped = shape_match_context(&accumulated, 9, 3, Some(4));
assert_eq!(shaped.data, b"x___OK>");
assert_eq!(shaped.match_index, 4);
assert_eq!(shaped.needle_len, 3);
}
#[test]
fn shape_context_fewer_than_n_pre_match_bytes() {
let accumulated = b"OK>suffix".to_vec();
let shaped = shape_match_context(&accumulated, 0, 3, Some(128));
assert_eq!(shaped.data, b"OK>");
assert_eq!(shaped.match_index, 0);
}
#[test]
fn shape_context_none_returns_full_buffer() {
let accumulated = b"prefix___OK>suffix".to_vec();
let shaped = shape_match_context(&accumulated, 9, 3, None);
assert_eq!(shaped.data, accumulated);
assert_eq!(shaped.match_index, 9);
}
#[test]
fn shape_context_zero_amount_returns_only_matched_bytes() {
let accumulated = b"prefix___OK>suffix".to_vec();
let shaped = shape_match_context(&accumulated, 9, 3, Some(0));
assert_eq!(shaped.data, b"OK>");
assert_eq!(shaped.match_index, 0);
}
#[test]
fn shape_context_match_index_remains_relative_to_returned_payload() {
let accumulated = b"AAAAAAAAAOK>".to_vec();
let shaped = shape_match_context(&accumulated, 9, 3, Some(5));
assert_eq!(shaped.data, b"AAAAAOK>");
assert_eq!(shaped.match_index, 5);
}
#[test]
fn byte_matcher_with_context_stores_amount() {
let m = Matcher::new_literal(b"OK>".to_vec())
.map(|m| m.with_context(Some(64)))
.unwrap();
assert_eq!(m.context_amount(), Some(64));
}
#[test]
fn byte_matcher_with_context_none_same_as_new() {
let m = Matcher::new_literal(b"OK>".to_vec())
.map(|m| m.with_context(None))
.unwrap();
assert_eq!(m.context_amount(), None);
}
#[test]
fn byte_matcher_is_empty_on_fresh_instance() {
let m = Matcher::new_literal(b"OK>".to_vec()).unwrap();
assert!(m.is_empty());
}
#[test]
fn byte_matcher_is_not_empty_after_push() {
let mut m = Matcher::new_literal(b"OK>".to_vec()).unwrap();
m.push(b"hello");
assert!(!m.is_empty());
}
#[test]
fn validate_match_request_passes_context_through() {
let req = MatchRequest {
pattern: "OK>".into(),
config: MatchConfig {
mode: MatchMode::LiteralSubstring,
pattern_encoding: PatternEncoding::Utf8,
context_amount_of_matched_bytes: Some(128),
},
};
let matcher = validate_match_request(&req).unwrap();
assert_eq!(matcher.context_amount(), Some(128));
}
#[test]
fn regex_matches_simple_pattern() {
let mut m = Matcher::Regex {
re: regex::bytes::Regex::new("world").unwrap(),
window: Vec::new(),
context_amount: None,
base: 0,
};
assert_eq!(m.push(b"hello "), MatchResult::NoMatch);
assert_eq!(m.push(b"world"), MatchResult::Found(6));
}
#[test]
fn regex_matches_wildcard_dot() {
let mut m = Matcher::Regex {
re: regex::bytes::Regex::new("po.g").unwrap(),
window: Vec::new(),
context_amount: None,
base: 0,
};
assert_eq!(m.push(b"test"), MatchResult::NoMatch);
assert_eq!(m.push(b"pong"), MatchResult::Found(4));
}
#[test]
fn regex_no_match_returns_no_match() {
let mut m = Matcher::Regex {
re: regex::bytes::Regex::new("world").unwrap(),
window: Vec::new(),
context_amount: None,
base: 0,
};
assert_eq!(m.push(b"hello moon"), MatchResult::NoMatch);
}
#[test]
fn validate_match_request_regex_utf8() {
let req = MatchRequest {
pattern: "po.g".into(),
config: MatchConfig {
mode: MatchMode::Regex,
pattern_encoding: PatternEncoding::Utf8,
context_amount_of_matched_bytes: None,
},
};
let matcher = validate_match_request(&req).unwrap();
assert!(matcher.needle_len().is_none()); }
#[test]
fn validate_match_request_regex_invalid_rejected() {
let req = MatchRequest {
pattern: "[invalid".into(),
config: MatchConfig {
mode: MatchMode::Regex,
pattern_encoding: PatternEncoding::Utf8,
context_amount_of_matched_bytes: None,
},
};
assert!(validate_match_request(&req).is_err());
}
#[test]
fn glob_matches_line() {
let mut m = Matcher::Glob {
pat: glob::Pattern::new("pong").unwrap(),
window: Vec::new(),
context_amount: None,
base: 0,
first_line_partial: false,
};
assert_eq!(m.push(b"boot\npong\nready"), MatchResult::Found(5));
}
#[test]
fn glob_matches_line_with_crlf_endings() {
let mut m = Matcher::Glob {
pat: glob::Pattern::new("pong").unwrap(),
window: Vec::new(),
context_amount: None,
base: 0,
first_line_partial: false,
};
assert_eq!(m.push(b"boot\r\npong\r\nready"), MatchResult::Found(6));
}
#[test]
fn glob_matches_first_line_with_crlf() {
let mut m = Matcher::Glob {
pat: glob::Pattern::new("boot").unwrap(),
window: Vec::new(),
context_amount: None,
base: 0,
first_line_partial: false,
};
assert_eq!(m.push(b"boot\r\npong\r\nready"), MatchResult::Found(0));
}
#[test]
fn glob_matches_last_partial_line() {
let mut m = Matcher::Glob {
pat: glob::Pattern::new("pong").unwrap(),
window: Vec::new(),
context_amount: None,
base: 0,
first_line_partial: false,
};
assert_eq!(m.push(b"boot\r\npong"), MatchResult::Found(6));
}
#[test]
fn glob_no_match_returns_no_match() {
let mut m = Matcher::Glob {
pat: glob::Pattern::new("pong").unwrap(),
window: Vec::new(),
context_amount: None,
base: 0,
first_line_partial: false,
};
assert_eq!(m.push(b"boot\r\nready\r\ndone"), MatchResult::NoMatch);
}
#[test]
fn glob_matches_wildcard_pattern() {
let mut m = Matcher::Glob {
pat: glob::Pattern::new("error*").unwrap(),
window: Vec::new(),
context_amount: None,
base: 0,
first_line_partial: false,
};
assert_eq!(
m.push(b"boot\r\nerror: flash failed\r\nready"),
MatchResult::Found(6)
);
}
#[test]
fn validate_match_request_glob_invalid_rejected() {
let req = MatchRequest {
pattern: "[unclosed".into(),
config: MatchConfig {
mode: MatchMode::Glob,
pattern_encoding: PatternEncoding::Utf8,
context_amount_of_matched_bytes: None,
},
};
assert!(validate_match_request(&req).is_err());
}
#[test]
fn retained_window_limit_uses_mode_overlap_allowance() {
let literal = Matcher::new_literal(b"OK>".to_vec()).unwrap();
assert_eq!(literal.retained_window_limit(16), 18);
let one = Matcher::new_literal(b"O".to_vec()).unwrap();
assert_eq!(one.retained_window_limit(16), 16);
assert_eq!(one.retained_window_limit(0), 0);
let re = Matcher::Regex {
re: regex::bytes::Regex::new("o").unwrap(),
window: Vec::new(),
context_amount: None,
base: 0,
};
assert_eq!(
re.retained_window_limit(16),
16 + REGEX_GLOB_OVERLAP_ALLOWANCE
);
}
#[test]
fn push_bounded_literal_spanning_chunks_matches_global_index() {
let mut m = Matcher::new_literal(b"XYZ".to_vec())
.map(|m| m.with_context(None))
.unwrap();
assert_eq!(m.push_bounded(b"0123456789A", 8), MatchResult::NoMatch);
assert_eq!(m.len(), 10);
assert_eq!(m.retained_window_limit(8), 10);
assert_eq!(
m.push_bounded(b"BCXYZ", 8),
MatchResult::Found(13),
"match index must be global, not window-local"
);
}
#[test]
fn push_bounded_repeated_no_match_keeps_window_within_limit() {
let mut m = Matcher::new_literal(b"XYZ".to_vec()).unwrap();
for i in 0..20u8 {
let chunk = [i, i + 1, i + 2, i + 3, i + 4];
assert_eq!(m.push_bounded(&chunk, 16), MatchResult::NoMatch);
assert!(
m.len() <= m.retained_window_limit(16),
"window {} exceeds limit {} after push {}",
m.len(),
m.retained_window_limit(16),
i
);
}
}
#[test]
fn push_bounded_zero_and_one_byte_literal_no_underflow() {
let mut one = Matcher::new_literal(b"B".to_vec()).unwrap();
assert_eq!(one.push_bounded(b"ab", 3), MatchResult::NoMatch);
assert_eq!(one.push_bounded(b"cdB", 3), MatchResult::Found(4));
assert_eq!(one.len(), 3, "retained window must not exceed max=3");
let mut zero = Matcher::new_literal(b"A".to_vec()).unwrap();
assert_eq!(zero.push_bounded(b"A", 0), MatchResult::Found(0));
assert!(zero.is_empty());
assert_eq!(zero.push_bounded(b"xyz", 0), MatchResult::NoMatch);
assert!(zero.is_empty());
}
#[test]
fn truncate_front_advances_global_base_exactly() {
let mut m = Matcher::new_literal(b"OK>".to_vec()).unwrap();
assert_eq!(m.push(b"ABCDEF"), MatchResult::NoMatch);
m.truncate_front(4); assert_eq!(m.push(b"OK>"), MatchResult::Found(6)); m.truncate_front(2); assert_eq!(m.check(), MatchResult::NoMatch);
}
#[test]
fn reset_window_restores_frame_local_index_zero() {
let mut m = Matcher::new_literal(b"OK>".to_vec()).unwrap();
m.push(b"AAAABBB");
m.truncate_front(3);
m.push(b"X");
assert_eq!(m.push(b"OK>"), MatchResult::Found(8));
m.reset_window();
assert!(m.is_empty());
assert_eq!(m.check(), MatchResult::NoMatch);
assert_eq!(m.push(b"OK>"), MatchResult::Found(0));
}
#[test]
fn push_bounded_literal_context_capped_at_max_buffered_bytes() {
let mut m = Matcher::new_literal(b"XYZ".to_vec())
.map(|m| m.with_context(Some(4096)))
.unwrap();
let hist = vec![b'a'; 100];
assert_eq!(m.push_bounded(&hist, 8), MatchResult::NoMatch);
assert_eq!(m.len(), 10);
assert_eq!(m.push_bounded(b"XYZ", 8), MatchResult::Found(100));
let shaped = m.shape_literal_match_context(100).expect("saved context");
assert_eq!(shaped.data, b"aaaaaaaaXYZ");
assert_eq!(shaped.match_index, 8);
assert_eq!(shaped.needle_len, 3);
let mut n = Matcher::new_literal(b"XYZ".to_vec())
.map(|m| m.with_context(Some(4096)))
.unwrap();
assert_eq!(n.push_bounded(&hist, 8), MatchResult::NoMatch);
assert_eq!(n.push_bounded(b"XYZ", 3), MatchResult::Found(100));
let shaped = n.shape_literal_match_context(100).expect("saved context");
assert_eq!(shaped.data, b"aaaXYZ");
assert_eq!(shaped.match_index, 3);
assert_eq!(shaped.needle_len, 3);
}
#[test]
fn push_saves_frame_local_literal_context() {
let mut m = Matcher::new_literal(b"beta".to_vec())
.map(|m| m.with_context(Some(16)))
.unwrap();
assert_eq!(m.push(b"alpha"), MatchResult::NoMatch);
assert!(m.shape_literal_match_context(0).is_none());
m.reset_window();
assert_eq!(m.push(b"xxbeta"), MatchResult::Found(2));
let shaped = m.shape_literal_match_context(2).expect("saved context");
assert_eq!(shaped.data, b"xxbeta");
assert_eq!(shaped.match_index, 2);
assert_eq!(shaped.needle_len, 4);
assert!(m.shape_literal_match_context(3).is_none());
m.truncate_front(2); assert_eq!(m.push(b"zz"), MatchResult::NoMatch);
assert!(m.shape_literal_match_context(2).is_none());
m.reset_window();
assert!(m.shape_literal_match_context(2).is_none());
assert_eq!(m.push(b"beta"), MatchResult::Found(0));
let shaped = m.shape_literal_match_context(0).expect("saved context");
assert_eq!(shaped.data, b"beta");
assert_eq!(shaped.match_index, 0);
assert_eq!(shaped.needle_len, 4);
}
#[test]
fn bounded_context_at_exact_truncation_boundary_is_exact() {
let mut m = Matcher::new_literal(b"XYZ".to_vec())
.map(|m| m.with_context(Some(4)))
.unwrap();
assert_eq!(m.push_bounded(b"abcdefghij", 6), MatchResult::NoMatch);
assert_eq!(m.len(), 8);
assert_eq!(m.push_bounded(b"XYZ", 6), MatchResult::Found(10));
let shaped = m.shape_literal_match_context(10).expect("saved context");
assert_eq!(shaped.data, b"ghijXYZ");
assert_eq!(shaped.match_index, 4);
assert_eq!(shaped.needle_len, 3);
assert!(m.shape_literal_match_context(11).is_none());
assert!(m.shape_literal_match_context(9).is_none());
assert_eq!(m.push_bounded(b"qq", 6), MatchResult::Found(10));
assert!(m.shape_literal_match_context(10).is_some());
m.reset_window();
assert!(m.shape_literal_match_context(10).is_none());
let mut fresh = Matcher::new_literal(b"XYZ".to_vec())
.map(|m| m.with_context(Some(4)))
.unwrap();
assert_eq!(fresh.push_bounded(b"abc", 6), MatchResult::NoMatch);
assert!(fresh.shape_literal_match_context(0).is_none());
let re = Matcher::Regex {
re: regex::bytes::Regex::new("xyz").unwrap(),
window: Vec::new(),
context_amount: Some(4),
base: 0,
};
assert!(re.shape_literal_match_context(0).is_none());
}
#[test]
fn regex_matches_across_chunk_splits_within_retained_cap() {
let mut m = Matcher::Regex {
re: regex::bytes::Regex::new("world").unwrap(),
window: Vec::new(),
context_amount: None,
base: 0,
};
assert_eq!(m.push_bounded(b"hello wor", 64), MatchResult::NoMatch);
assert_eq!(m.push_bounded(b"ld", 64), MatchResult::Found(6));
}
#[test]
fn glob_matches_across_chunk_splits_within_retained_cap() {
let mut m = Matcher::Glob {
pat: glob::Pattern::new("pong").unwrap(),
window: Vec::new(),
context_amount: None,
base: 0,
first_line_partial: false,
};
assert_eq!(m.push_bounded(b"boot\n", 64), MatchResult::NoMatch);
assert_eq!(m.push_bounded(b"pong\nready", 64), MatchResult::Found(5));
}
#[test]
fn glob_truncated_mid_line_does_not_false_match() {
let mut m = Matcher::Glob {
pat: glob::Pattern::new("dy").unwrap(),
window: Vec::new(),
context_amount: None,
base: 0,
first_line_partial: false,
};
assert_eq!(m.push(b"ready\n"), MatchResult::NoMatch);
m.truncate_front(3); assert_eq!(
m.check(),
MatchResult::NoMatch,
"partial line must not match"
);
assert_eq!(m.push(b"xyz\n"), MatchResult::NoMatch);
let mut n = Matcher::Glob {
pat: glob::Pattern::new("zz").unwrap(),
window: Vec::new(),
context_amount: None,
base: 0,
first_line_partial: false,
};
assert_eq!(n.push(b"ab\ncd\n"), MatchResult::NoMatch);
n.truncate_front(3); assert_eq!(n.push(b"zz\n"), MatchResult::Found(6));
}
#[test]
fn glob_bounded_push_truncation_keeps_global_line_indexes() {
let mut m = Matcher::Glob {
pat: glob::Pattern::new("ready").unwrap(),
window: Vec::new(),
context_amount: None,
base: 0,
first_line_partial: false,
};
let junk = vec![b'x'; 200];
let mut fed = 0usize;
let mut chunk = junk.clone();
chunk.extend_from_slice(b"\n");
assert_eq!(m.push_bounded(&chunk, 64), MatchResult::NoMatch);
fed += chunk.len();
let chunk2 = vec![b'y'; 200];
let mut chunk2 = chunk2;
chunk2.extend_from_slice(b"\nready\n");
let result = m.push_bounded(&chunk2, 64);
let ready_offset = fed + 200 + 1; assert_eq!(result, MatchResult::Found(ready_offset));
assert!(
m.len() <= m.retained_window_limit(64),
"window {} exceeds limit {}",
m.len(),
m.retained_window_limit(64)
);
}
#[test]
fn push_bounded_glob_partial_first_line_after_boundary_truncation() {
let mut m = Matcher::Glob {
pat: glob::Pattern::new("pong").unwrap(),
window: Vec::new(),
context_amount: None,
base: 0,
first_line_partial: false,
};
assert_eq!(m.push(b"boot\nxxxx\n"), MatchResult::NoMatch);
m.truncate_front(5); assert_eq!(
m.push(b"pong\n"),
MatchResult::Found(10),
"complete line after boundary truncation matches at global index"
);
}
}