// MoonBit's JSON parser refuses an escaped surrogate that has no partner, such
// as half an emoji. JavaScript accepts it, and `JSON.stringify` writes it, so a
// saved file can hold one.

///|
/// The value of the escape `\uXXXX` that starts at `at`, if there is one.
fn unicode_escape(text : String, at : Int32) -> Int32? {
  if at + 6 > text.length() || text[at] != '\\' || text[at + 1] != 'u' {
    return None
  }
  let mut value = 0
  for i in (at + 2)..<(at + 6) {
    let c = text[i].to_int()
    let digit = if c >= '0' && c <= '9' {
      c - '0'
    } else if c >= 'a' && c <= 'f' {
      c - 'a' + 10
    } else if c >= 'A' && c <= 'F' {
      c - 'A' + 10
    } else {
      return None
    }
    value = value * 16 + digit
  }
  Some(value)
}

///|
/// Replaces each escaped surrogate that has no partner with `�`, the
/// character it becomes when the official SVG is saved to a file.
fn replace_lone_surrogates(text : String) -> String {
  if !text.contains("\\ud") && !text.contains("\\uD") {
    return text
  }
  let out = StringBuilder()
  // Text up to `copied` is already in `out`.
  let mut copied = 0
  let mut i = 0
  while i < text.length() {
    if text[i] != '\\' {
      i += 1
      continue
    }
    match unicode_escape(text, i) {
      Some(high) if high >= 0xD800 && high <= 0xDBFF =>
        match unicode_escape(text, i + 6) {
          Some(low) if low >= 0xDC00 && low <= 0xDFFF => i += 12
          _ => {
            out.write_view(text.clamped_view(start=copied, end=i))
            out.write_string("\\ufffd")
            i += 6
            copied = i
          }
        }
      Some(low) if low >= 0xDC00 && low <= 0xDFFF => {
        out.write_view(text.clamped_view(start=copied, end=i))
        out.write_string("\\ufffd")
        i += 6
        copied = i
      }
      Some(_) => i += 6
      // Another escape, such as `\\` or `\n`: both characters belong to it.
      None => i += 2
    }
  }
  out.write_view(text.clamped_view(start=copied))
  out.to_string()
}