///|
fn find_crlf(data : BytesView, start : Int32) -> Int32? {
  let n = data.length()
  let mut i = start
  while i + 1 < n {
    if data[i] == b'\r' && data[i + 1] == b'\n' {
      return Some(i)
    }
    i = i + 1
  }
  None
}

///|
fn parse_bulk_at(
  data : BytesView,
  len_start : Int32,
  len_end : Int32,
  after : Int32,
) -> (RedisValue, Int32)? {
  match parse_int_bytes(data, len_start, len_end) {
    None => Some((Error("Invalid bulk length"), after))
    Some(len) =>
      if len < 0 {
        Some((BulkString(None), after))
      } else if data.length() < after + len + 2 {
        None
      } else {
        Some(
          (
            BulkString(Some(decode_span(data, after, after + len))),
            after + len + 2,
          ),
        )
      }
  }
}

///|
fn parse_array_at(
  data : BytesView,
  count_start : Int32,
  count_end : Int32,
  after : Int32,
) -> (RedisValue, Int32)? {
  match parse_int_bytes(data, count_start, count_end) {
    None => Some((Error("Invalid array count"), after))
    Some(count) =>
      if count < 0 {
        Some((Array([]), after))
      } else {
        let items : Array[RedisValue] = []
        let mut pos = after
        let mut i = 0
        while i < count {
          match parse_reply(data, pos) {
            None => return None
            Some((value, next)) => {
              items.push(value)
              pos = next
            }
          }
          i = i + 1
        }
        Some((Array(items), pos))
      }
  }
}

///|
/// Parse the single reply that starts at `pos`; `None` means the buffer does not
/// hold all of it yet.
fn parse_reply(data : BytesView, pos : Int32) -> (RedisValue, Int32)? {
  if pos >= data.length() {
    return None
  }
  let tag = data[pos]
  if !(tag == b'+' || tag == b'-' || tag == b':' || tag == b'$' || tag == b'*') {
    return Some((Error("Unknown response type"), pos))
  }
  match find_crlf(data, pos + 1) {
    None => None
    Some(crlf) => {
      let after = crlf + 2
      if tag == b'+' {
        Some((SimpleString(decode_span(data, pos + 1, crlf)), after))
      } else if tag == b'-' {
        Some((Error(decode_span(data, pos + 1, crlf)), after))
      } else if tag == b':' {
        match parse_int_bytes(data, pos + 1, crlf) {
          Some(number) => Some((Integer(number), after))
          None => Some((Error("Invalid integer"), after))
        }
      } else if tag == b'$' {
        parse_bulk_at(data, pos + 1, crlf, after)
      } else {
        parse_array_at(data, pos + 1, crlf, after)
      }
    }
  }
}

///|
/// Parse a complete RESP2 reply held in `response`.
///
/// Frame lengths are byte counts, so the text is re-encoded to UTF-8 before being
/// walked. An input that stops mid-frame yields `Error("Incomplete RESP reply")`
/// rather than a silently shortened value.
pub fn parse_redis_response(response : String) -> RedisValue {
  if response.length() == 0 {
    return Error("Empty response")
  }
  let data = @encoding/utf8.encode(response)
  match parse_reply(data, 0) {
    None => Error("Incomplete RESP reply")
    Some((value, _)) => value
  }
}