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
use super::Chunker;
use crate::config::{InputFormat, MultilineConfig, MultilineStrategy};
use regex::Regex;
/// Multi-line chunker that implements various strategies for detecting event boundaries
pub struct MultilineChunker {
config: MultilineConfig,
buffer: Vec<String>,
regex: Option<Regex>,
input_format: InputFormat,
}
impl MultilineChunker {
pub fn new(config: MultilineConfig, input_format: InputFormat) -> Result<Self, String> {
let regex = match &config.strategy {
MultilineStrategy::Timestamp { pattern } => {
Some(Regex::new(pattern).map_err(|e| format!("Invalid timestamp regex: {}", e))?)
}
MultilineStrategy::Start { pattern } => {
Some(Regex::new(pattern).map_err(|e| format!("Invalid start regex: {}", e))?)
}
MultilineStrategy::End { pattern } => {
Some(Regex::new(pattern).map_err(|e| format!("Invalid end regex: {}", e))?)
}
MultilineStrategy::Boundary { start, end: _ } => {
// We'll compile both patterns, but store start pattern here
Some(
Regex::new(start)
.map_err(|e| format!("Invalid boundary start regex: {}", e))?,
)
}
MultilineStrategy::Whole => None,
_ => None,
};
Ok(Self {
config,
buffer: Vec::new(),
regex,
input_format,
})
}
/// Check if this line starts a new event based on the strategy
fn starts_new_event(&self, line: &str) -> bool {
match &self.config.strategy {
MultilineStrategy::Timestamp { .. } => {
if let Some(ref regex) = self.regex {
regex.is_match(line)
} else {
false
}
}
MultilineStrategy::Indent {
spaces,
tabs,
mixed,
} => {
// A new event starts when the line is NOT indented
!self.is_indented(line, *spaces, *tabs, *mixed)
}
MultilineStrategy::Start { .. } => {
if let Some(ref regex) = self.regex {
regex.is_match(line)
} else {
false
}
}
MultilineStrategy::End { .. } => {
// For end strategy, we look at the previous line in the buffer
false // New events don't start based on current line
}
MultilineStrategy::Boundary { .. } => {
if let Some(ref regex) = self.regex {
regex.is_match(line)
} else {
false
}
}
MultilineStrategy::Backslash { .. } => {
// New events start when previous line doesn't end with continuation char
false // Logic handled elsewhere
}
MultilineStrategy::Whole => {
// Whole strategy never starts new events during feed - everything gets buffered
false
}
}
}
/// Check if this line ends the current event based on the strategy
fn ends_current_event(&self, line: &str) -> bool {
match &self.config.strategy {
MultilineStrategy::End { pattern: _ } => {
if let Some(ref regex) = self.regex {
regex.is_match(line)
} else {
false
}
}
MultilineStrategy::Boundary { end, .. } => {
if let Ok(end_regex) = Regex::new(end) {
end_regex.is_match(line)
} else {
false
}
}
MultilineStrategy::Backslash { char } => {
// Event continues if line ends with continuation character (ignoring trailing newlines)
let trimmed = line.trim_end_matches('\n').trim_end_matches('\r');
!trimmed.ends_with(*char)
}
MultilineStrategy::Whole => {
// Whole strategy never ends current event during feed - everything gets buffered
false
}
_ => false,
}
}
/// Check if a line is indented according to the indent strategy
fn is_indented(&self, line: &str, spaces: Option<u32>, tabs: bool, mixed: bool) -> bool {
if line.is_empty() {
return false; // Empty lines are not considered indented
}
if mixed {
// Any whitespace counts as indentation
line.starts_with(' ') || line.starts_with('\t')
} else if tabs {
// Only tabs count
line.starts_with('\t')
} else if let Some(min_spaces) = spaces {
// Specific number of spaces required
let leading_spaces = line.chars().take_while(|&c| c == ' ').count() as u32;
leading_spaces >= min_spaces
} else {
// Default: any space-based indentation
line.starts_with(' ')
}
}
/// Clean backslash continuation sequences from a string
fn clean_backslash_continuations(&self, input: &str, continuation_char: char) -> String {
let mut result = String::with_capacity(input.len());
let lines: Vec<&str> = input.split('\n').collect();
for (i, line) in lines.iter().enumerate() {
let trimmed = line.trim_end_matches('\r');
if trimmed.ends_with(continuation_char) {
// Remove the continuation character and join directly with the next line
let without_continuation = &trimmed[..trimmed.len() - continuation_char.len_utf8()];
result.push_str(without_continuation);
// Don't add space - continuation means direct concatenation
} else {
result.push_str(trimmed);
}
// Only add space between lines if current line doesn't end with continuation
// and this isn't the last line
if !trimmed.ends_with(continuation_char) && i < lines.len() - 1 {
result.push(' ');
}
}
result
}
/// Flush the current buffer and return the event
fn flush_buffer(&mut self) -> Option<String> {
if self.buffer.is_empty() {
None
} else {
let joined = match &self.config.strategy {
MultilineStrategy::Whole => {
// Join with newlines to preserve line structure for whole file reading
self.buffer.join("\n")
}
_ => {
// Lines already contain newlines for other strategies
self.buffer.join("")
}
};
// Apply format-aware line cleaning
let result = match &self.config.strategy {
MultilineStrategy::Backslash { char } => {
// Always clean backslash continuations regardless of format
self.clean_backslash_continuations(&joined, *char)
}
_ => {
// For other strategies, clean based on input format
match self.input_format {
InputFormat::Raw => {
// Preserve newlines for raw format - this is the new use case
joined
}
_ => {
// Replace newlines with spaces for all other formats (including line)
joined.replace('\n', " ").replace('\r', "")
}
}
}
};
self.buffer.clear();
Some(result)
}
}
}
impl Chunker for MultilineChunker {
fn feed_line(&mut self, line: String) -> Option<String> {
// Whole strategy always buffers everything and never returns content during feed
if let MultilineStrategy::Whole = &self.config.strategy {
self.buffer.push(line);
return None;
}
// Backslash strategy has different logic - we need to add the line first,
// then check if the event should end
if let MultilineStrategy::Backslash { .. } = &self.config.strategy {
// Add the line to buffer first
self.buffer.push(line);
// Check if this line (the one we just added) ends the event
if let Some(last_line) = self.buffer.last() {
if self.ends_current_event(last_line) {
// Event is complete, flush the buffer
return self.flush_buffer();
}
}
// Event continues, return None
return None;
}
// For all other strategies, use the original logic
let should_flush = match &self.config.strategy {
MultilineStrategy::End { .. } | MultilineStrategy::Boundary { .. } => {
// For end/boundary strategies, check if current line ends the event
self.ends_current_event(&line)
}
_ => {
// For timestamp, indent, and start strategies, check if current line starts a new event
!self.buffer.is_empty() && self.starts_new_event(&line)
}
};
let result = if should_flush {
self.flush_buffer()
} else {
None
};
// Add the new line to buffer
self.buffer.push(line);
result
}
fn flush(&mut self) -> Option<String> {
self.flush_buffer()
}
fn has_pending(&self) -> bool {
!self.buffer.is_empty()
}
}
/// Create a chunker based on multiline configuration
pub fn create_multiline_chunker(
config: &MultilineConfig,
input_format: InputFormat,
) -> Result<Box<dyn Chunker>, String> {
let chunker = MultilineChunker::new(config.clone(), input_format)?;
Ok(Box::new(chunker))
}