scrolling_window_pattern_matcher 2.0.0

A flexible pattern matching library with extractor-driven architecture for dynamic behavior modification.
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
# ScrollingWindowPatternMatcher


A flexible pattern matching library for Rust with an advanced extractor system for dynamic behavior modification. This library allows you to create complex patterns that match against sequences of data, with powerful extractor functions that can modify matching behavior at runtime.

## 🚨 Major Version 2.0 Rewrite


**This is a complete rewrite from version 1.x with breaking API changes.** The previous field-based pattern syntax has been replaced with a settings-based approach, and the callback system has been replaced with a more powerful extractor architecture.

### Migration from 1.x


The API has fundamentally changed. Please see the examples and documentation below for the new approach.

## ✨ Features


- **Extractor-driven architecture** - Dynamic modification of matching behavior through extractor functions
- **Settings-based configuration** - Clean builder pattern for pattern element configuration
- **Rich pattern elements** - Values, functions, pattern references, wildcards, and nested repeats
- **Advanced extractor actions** - Continue, Skip, Jump, pattern manipulation, and flow control
- **Comprehensive error handling** - Detailed error types with proper error propagation
- **Zero-copy when possible** - Efficient matching with minimal allocations
- **Priority-based matching** - Control pattern matching order with priority settings

## 🚀 Quick Start


```rust
use scrolling_window_pattern_matcher::{ElementSettings, Matcher, PatternElement};

// Create a matcher
let mut matcher = Matcher::new();

// Add a pattern to find the value 42
matcher.add_pattern(
    "find_42".to_string(),
    vec![PatternElement::Value {
        value: 42,
        settings: Some(ElementSettings::new().min_repeat(1).max_repeat(1)),
    }]
);

// Match against data
let data = vec![1, 42, 3, 42, 5];
let result = matcher.run(&data);
assert!(result.is_ok());
```

## 🏗️ Pattern Elements


### Value


Matches a specific value:

```rust
PatternElement::Value {
    value: 42,
    settings: Some(
        ElementSettings::new()
            .min_repeat(1)     // Must match at least this many times
            .max_repeat(3)     // Match at most this many times
            .greedy(true)      // Match as many as possible (true) or as few as possible (false)
            .priority(10)      // Lower numbers = higher priority
    ),
}
```

### Function


Matches using custom logic:

```rust
PatternElement::Function {
    function: Box::new(|x: &i32| x % 2 == 0),  // Custom predicate function
    settings: Some(
        ElementSettings::new()
            .min_repeat(1)
            .max_repeat(5)
            .greedy(true)
    ),
}
```

### Any


Wildcard matching:

```rust
PatternElement::Any {
    settings: Some(
        ElementSettings::new()
            .min_repeat(1)     // Match any 1-3 consecutive items
            .max_repeat(3)
            .greedy(false)
    ),
}
```

### Pattern Reference


References another named pattern:

```rust
PatternElement::Pattern {
    pattern: "other_pattern_name".to_string(),
    settings: Some(ElementSettings::new().min_repeat(1).max_repeat(1)),
}
```

### Repeat


Repeats a nested pattern element:

```rust
PatternElement::Repeat {
    element: Box::new(PatternElement::Value {
        value: 5,
        settings: None,
    }),
    settings: Some(
        ElementSettings::new()
            .min_repeat(2)
            .max_repeat(4)
            .greedy(true)
    ),
}
```

## ⚡ Extractor System


The extractor system is the core feature that allows dynamic modification of matching behavior:

### Basic Extractor


```rust
use scrolling_window_pattern_matcher::{ExtractorAction, MatchState};

let extractor = Box::new(|state: &MatchState<i32>| {
    println!("Matched at position {}: {:?}",
             state.current_position,
             state.matched_items);
    Ok(ExtractorAction::Continue)
});

let pattern = vec![PatternElement::Value {
    value: 42,
    settings: Some(ElementSettings::new().extractor(extractor)),
}];
```

### Extractor Actions


#### Continue


Continue normal matching:

```rust
Ok(ExtractorAction::Continue)
```

#### Skip


Skip ahead by N positions:

```rust
Ok(ExtractorAction::Skip(3))  // Skip 3 positions ahead
```

#### Jump


Jump relative to current position:

```rust
Ok(ExtractorAction::Jump(-2))  // Jump back 2 positions
Ok(ExtractorAction::Jump(5))   // Jump forward 5 positions
```

#### Pattern Manipulation


Add or remove patterns dynamically:

```rust
// Add a new pattern
Ok(ExtractorAction::AddPattern(
    "new_pattern".to_string(),
    Pattern::new(vec![/* pattern elements */])
))

// Remove a pattern
Ok(ExtractorAction::RemovePattern("old_pattern".to_string()))
```

#### Flow Control


```rust
Ok(ExtractorAction::StopMatching)           // Stop all matching
Ok(ExtractorAction::DiscardPartialMatch)    // Discard current match
Ok(ExtractorAction::RestartFrom(0))         // Restart from specific position
```

### Match State Information


Extractors receive rich context information:

```rust
let extractor = Box::new(|state: &MatchState<i32>| {
    println!("Current position: {}", state.current_position);
    println!("Matched items: {:?}", state.matched_items);
    println!("Pattern name: {}", state.pattern_name);
    println!("Element index: {}", state.element_index);
    println!("Input length: {}", state.input_length);
    Ok(ExtractorAction::Continue)
});
```

## 🔧 Complex Examples


### Multi-element Pattern


```rust
// Pattern: value 1, then any item, then value 3
matcher.add_pattern(
    "one_any_three".to_string(),
    vec![
        PatternElement::Value {
            value: 1,
            settings: Some(ElementSettings::new().min_repeat(1).max_repeat(1)),
        },
        PatternElement::Any {
            settings: Some(ElementSettings::new().min_repeat(1).max_repeat(1)),
        },
        PatternElement::Value {
            value: 3,
            settings: Some(ElementSettings::new().min_repeat(1).max_repeat(1)),
        },
    ]
);
```

### Advanced Extractor Usage


```rust
use scrolling_window_pattern_matcher::{ExtractorAction, ExtractorError, MatchState};

// Extractor that logs matches and skips ahead
let logging_extractor = Box::new(|state: &MatchState<i32>| -> Result<ExtractorAction<i32>, ExtractorError> {
    println!("🎯 Match found at position {}: {:?}",
             state.current_position,
             state.matched_items);

    // Skip ahead by 2 positions after each match
    Ok(ExtractorAction::Skip(2))
});

// Extractor that adds new patterns based on matched values
let dynamic_extractor = Box::new(|state: &MatchState<i32>| -> Result<ExtractorAction<i32>, ExtractorError> {
    if let Some(&first_value) = state.matched_items.first() {
        if first_value > 50 {
            let new_pattern = Pattern::new(vec![
                PatternElement::Value {
                    value: first_value + 10,
                    settings: Some(ElementSettings::new()),
                }
            ]);
            return Ok(ExtractorAction::AddPattern(
                format!("dynamic_{}", first_value),
                new_pattern
            ));
        }
    }
    Ok(ExtractorAction::Continue)
});
```

### Priority-based Matching


```rust
// Higher priority pattern (lower number = higher priority)
matcher.add_pattern(
    "high_priority".to_string(),
    vec![PatternElement::Value {
        value: 100,
        settings: Some(
            ElementSettings::new()
                .priority(1)  // High priority
                .min_repeat(1)
                .max_repeat(1)
        ),
    }]
);

// Lower priority pattern
matcher.add_pattern(
    "low_priority".to_string(),
    vec![PatternElement::Any {
        settings: Some(
            ElementSettings::new()
                .priority(10)  // Lower priority
                .min_repeat(1)
                .max_repeat(1)
        ),
    }]
);
```

## 🌍 Real-World Examples


### Log Analysis


```rust
// Detect HTTP error codes
let error_detector = Box::new(|state: &MatchState<i32>| -> Result<ExtractorAction<i32>, ExtractorError> {
    if let Some(&code) = state.matched_items.first() {
        match code {
            400..=499 => println!("⚠️  Client Error detected: {}", code),
            500..=599 => println!("🚨 Server Error detected: {}", code),
            _ => {}
        }
    }
    Ok(ExtractorAction::Continue)
});

matcher.add_pattern(
    "http_errors".to_string(),
    vec![PatternElement::Function {
        function: Box::new(|&code| (400..=599).contains(&code)),
        settings: Some(ElementSettings::new().extractor(error_detector)),
    }]
);
```

### Network Traffic Analysis


```rust
// Detect potential port scanning (rapid consecutive port accesses)
let scan_detector = Box::new(|state: &MatchState<i32>| -> Result<ExtractorAction<i32>, ExtractorError> {
    if state.matched_items.len() >= 3 {
        println!("🔍 Potential port scan detected: {} consecutive port accesses",
                 state.matched_items.len());
    }
    Ok(ExtractorAction::Continue)
});

matcher.add_pattern(
    "port_scan".to_string(),
    vec![PatternElement::Function {
        function: Box::new(|&port| (1..=65535).contains(&port)),
        settings: Some(
            ElementSettings::new()
                .min_repeat(3)
                .max_repeat(10)
                .greedy(true)
                .extractor(scan_detector)
        ),
    }]
);
```

## 🚨 Error Handling


The library provides comprehensive error handling:

```rust
use scrolling_window_pattern_matcher::{MatcherError, ExtractorError};

match matcher.run(&data) {
    Ok(()) => println!("Matching completed successfully"),
    Err(MatcherError::ExtractorError(ExtractorError::InvalidPosition(pos))) => {
        println!("Extractor tried to access invalid position: {}", pos);
    }
    Err(MatcherError::ExtractorError(ExtractorError::PatternNotFound(name))) => {
        println!("Extractor referenced non-existent pattern: {}", name);
    }
    Err(MatcherError::ExtractorError(ExtractorError::Message(msg))) => {
        println!("Extractor error: {}", msg);
    }
    Err(e) => println!("Other error: {}", e),
}
```

## 📚 API Reference


### Core Types


- `Matcher<T>` - Main matcher struct
- `PatternElement<T>` - Individual pattern elements (Value, Function, Any, Pattern, Repeat)
- `ElementSettings<T>` - Configuration for pattern elements
- `PatternSettings<T>` - Configuration for entire patterns
- `ExtractorAction<T>` - Actions that extractors can return
- `MatchState<T>` - Context information provided to extractors

### Matcher Methods


- `new()` - Create a new matcher
- `with_settings(settings)` - Create matcher with custom settings
- `add_pattern(name, elements)` - Add a pattern
- `add_pattern_with_settings(name, pattern)` - Add pattern with custom settings
- `remove_pattern(name)` - Remove a pattern
- `run(data)` - Execute matching on data slice

### Settings Builders


- `ElementSettings::new()` - Create element settings builder
- `PatternSettings::new()` - Create pattern settings builder

Builder methods: `.min_repeat()`, `.max_repeat()`, `.greedy()`, `.priority()`, `.extractor()`

## 🎯 Design Philosophy


This library prioritizes **flexibility and extensibility** through:

- **Extractor-driven architecture** - Extractors provide unlimited customization capabilities
- **Settings-based configuration** - Clean, discoverable API through builder patterns
- **Type safety** - Rust's type system prevents common pattern matching errors
- **Error transparency** - Comprehensive error types with detailed context
- **Performance awareness** - Efficient algorithms with minimal allocations where possible

## 📝 License


Licensed under either of:

- Apache License, Version 2.0 ([LICENSE-APACHE]LICENSE-APACHE)
- MIT License ([LICENSE-MIT]LICENSE-MIT)

at your option.

## 🔄 Breaking Changes from 1.x


- Complete API rewrite with settings-based configuration
- Callback system replaced with extractor architecture
- `match_window()` replaced with `run()` method
- Field-based pattern syntax replaced with settings builders
- Return type changed from `HashMap<String, Vec<T>>` to `Result<(), MatcherError>`
- Pattern matching results now handled through extractors rather than return values