Flush a text section as one or more chunks, splitting if too large.
(chunks: &mut Vec<TextChunk>, text: &str, start_line: usize, max_chars: usize)
| 245 | |
| 246 | /// Flush a text section as one or more chunks, splitting if too large. |
| 247 | fn flush_chunk(chunks: &mut Vec<TextChunk>, text: &str, start_line: usize, max_chars: usize) { |
| 248 | if text.len() <= max_chars { |
| 249 | chunks.push(TextChunk { |
| 250 | text: text.to_string(), |
| 251 | start_line, |
| 252 | }); |
| 253 | return; |
| 254 | } |
| 255 | |
| 256 | // Split by paragraph (blank lines) |
| 257 | let mut current = String::new(); |
| 258 | let mut line_offset = 0; |
| 259 | for (i, line) in text.lines().enumerate() { |
| 260 | if line.trim().is_empty() && !current.is_empty() && current.len() > max_chars / 2 { |
| 261 | chunks.push(TextChunk { |
| 262 | text: current.clone(), |
| 263 | start_line: start_line + line_offset, |
| 264 | }); |
| 265 | current.clear(); |
| 266 | line_offset = i + 1; |
| 267 | continue; |
| 268 | } |
| 269 | if !current.is_empty() { |
| 270 | current.push('\n'); |
| 271 | } |
| 272 | current.push_str(line); |
| 273 | |
| 274 | // Hard split if still too large |
| 275 | if current.len() > max_chars { |
| 276 | chunks.push(TextChunk { |
| 277 | text: current.clone(), |
| 278 | start_line: start_line + line_offset, |
| 279 | }); |
| 280 | current.clear(); |
| 281 | line_offset = i + 1; |
| 282 | } |
| 283 | } |
| 284 | if !current.is_empty() { |
| 285 | chunks.push(TextChunk { |
| 286 | text: current, |
| 287 | start_line: start_line + line_offset, |
| 288 | }); |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | /// Simple hash-based "embedding" for testing purposes. |
| 293 | /// |