// string_scan.hako — StringScanBox
// Escape-aware string scanning helpers for JSON/text processing.

using selfhost.shared.common.string_ops as StringOps

static box StringScanBox {
  // Return the single-character string at index i (empty if out of bounds)
  read_char(text, i) {
    if text == null { return "" }
    if i < 0 { return "" }
    local n = text.length()
    if i >= n { return "" }
    return text.substring(i, i+1)
  }
  // Find next unescaped double quote starting at or after pos
  find_quote(text, pos) {
    return me.find_unescaped(text, "\"", pos)
  }
  // Find substring starting from position (simple, non-escape-aware)
  index_of_from(text, needle, pos) {
    return StringOps.index_of_from(text, needle, pos)
  }
  // Find next occurrence of character `ch` in `text` at or after `pos`,
  // ignoring escaped occurrences (preceded by a backslash).
  find_unescaped(text, ch, pos) {
    if text == null { return -1 }
    if pos < 0 { pos = 0 }
    local n = text.length()
    local i = pos
    loop (i < n) {
      local c = me.read_char(text, i)
      if c == "\\" {
        // skip escape sequence
        i = i + 2
        continue
      }
      if c == ch { return i }
      i = i + 1
    }
    return -1
  }

  // Given a starting index at a double quote, find the closing quote index
  // respecting escape sequences; returns -1 if unterminated.
  scan_string_end(text, start) {
    if text == null { return -1 }
    if start < 0 || start >= text.length() { return -1 }
    if text.substring(start, start+1) != "\"" { return -1 }
    local i = start + 1
    local n = text.length()
    loop (i < n) {
      local c = me.read_char(text, i)
      if c == "\\" { i = i + 2  continue }
      if c == "\"" { return i }
      i = i + 1
    }
    return -1
  }
}
