MCPcopy Create free account
hub / github.com/AI45Lab/Code / find_balanced_range

Function find_balanced_range

core/src/llm/structured.rs:375–427  ·  view source on GitHub ↗

Byte range `[start, end)` of the first balanced `open..close` substring (quote-aware).

(text: &str, open: char, close: char)

Source from the content-addressed store, hash-verified

373
374/// Byte range `[start, end)` of the first balanced `open..close` substring (quote-aware).
375fn find_balanced_range(text: &str, open: char, close: char) -> Option<(usize, usize)> {
376 let bytes = text.as_bytes();
377 let open_byte = open as u8;
378 let close_byte = close as u8;
379
380 // Find the first unquoted occurrence of `open`
381 let mut in_string = false;
382 let mut escape_next = false;
383 let mut start = None;
384
385 for (i, &b) in bytes.iter().enumerate() {
386 if escape_next {
387 escape_next = false;
388 continue;
389 }
390 match b {
391 b'\\' if in_string => escape_next = true,
392 b'"' => in_string = !in_string,
393 _ if in_string => {}
394 _ if b == open_byte => {
395 start = Some(i);
396 break;
397 }
398 _ => {}
399 }
400 }
401
402 let start = start?;
403 let mut depth = 0i32;
404 in_string = false;
405 escape_next = false;
406
407 for (i, &b) in bytes[start..].iter().enumerate() {
408 if escape_next {
409 escape_next = false;
410 continue;
411 }
412 match b {
413 b'\\' if in_string => escape_next = true,
414 b'"' => in_string = !in_string,
415 _ if in_string => {}
416 _ if b == open_byte => depth += 1,
417 _ if b == close_byte => {
418 depth -= 1;
419 if depth == 0 {
420 return Some((start, start + i + 1));
421 }
422 }
423 _ => {}
424 }
425 }
426 None
427}
428
429/// Every top-level balanced `open..close` substring, in document order.
430///

Callers 2

find_balancedFunction · 0.85
find_all_balancedFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected