///|
priv struct HttpHead {
  code : Int32
  headers : Map[String, String]
  body_offset : Int32
}

///|
priv struct HttpBody {
  data : Bytes
  complete : Bool
}

///|
fn find_bytes(
  bytes : BytesView,
  needle : BytesView,
  start~ : Int32 = 0,
) -> Int32? {
  if bytes.length() < needle.length() {
    return None
  }
  for i in start..<=(bytes.length() - needle.length()) {
    if bytes[i:i + needle.length()] == needle {
      return Some(i)
    }
  }
  None
}

///|
fn http_head(bytes : BytesView) -> HttpHead? raise InputError {
  let mut start = 0
  // Ignore bounded informational responses; upgrade protocols are not supported.
  for _ in 0..<5 {
    let end = match find_bytes(bytes, b"\r\n\r\n", start~) {
      Some(end) => end
      None => {
        guard bytes.length() - start < 16384 else {
          raise InputError("HTTP headers exceed 16 KiB")
        }
        return None
      }
    }
    guard end - start <= 16384 else {
      raise InputError("HTTP headers exceed 16 KiB")
    }
    let text = @utf8.decode(bytes[start:end]) catch {
      _ => raise InputError("invalid HTTP header encoding")
    }
    let lines = text.split("\r\n").collect()
    let status = lines[0].split(" ").collect()
    guard status.length() >= 2 &&
      status[1].length() == 3 &&
      status[0] is ("HTTP/1.0" | "HTTP/1.1") else {
      raise InputError("response is not HTTP/1.x")
    }
    let code = decimal(status[1], 599)
    guard code >= 100 && code != 101 else {
      raise InputError("unsupported HTTP status")
    }
    let headers : Map[String, String] = Map([])
    guard lines.length() <= 129 else {
      raise InputError("too many HTTP headers")
    }
    for line in lines[1:] {
      guard line.split_once(":") is Some((name, value)) &&
        !name.is_empty() &&
        name
        .iter()
        .all(c => {
          c
          is ('a'..<='z'
          | 'A'..<='Z'
          | '0'..<='9'
          | '!'
          | '#'
          | '$'
          | '%'
          | '&'
          | '\''
          | '*'
          | '+'
          | '-'
          | '.'
          | '^'
          | '_'
          | '`'
          | '|'
          | '~')
        }) &&
        value
        .iter()
        .all(c => c == '\t' || (c.to_int() >= 32 && c.to_int() != 127)) else {
        raise InputError("invalid HTTP header")
      }
      let name = ascii_lower(name)
      if name is ("content-length" | "transfer-encoding" | "content-encoding") &&
        headers.contains(name) {
        raise InputError("ambiguous duplicate HTTP framing header")
      }
      headers[name] = value.trim().to_owned()
    }
    guard !(headers.contains("content-length") &&
      headers.contains("transfer-encoding")) else {
      raise InputError("ambiguous HTTP transfer length")
    }
    if code < 200 {
      start = end + 4
      continue
    }
    return Some({ code, headers, body_offset: end + 4, })
  }
  raise InputError("too many informational HTTP responses")
}

///|
fn hex_number(text : StringView, maximum : Int32) -> Int32 raise InputError {
  guard !text.is_empty() else { raise InputError("empty hexadecimal number") }
  let mut number = 0
  for c in text {
    let digit = match c {
      '0'..<='9' => c.to_int() - 48
      'a'..<='f' => c.to_int() - 87
      'A'..<='F' => c.to_int() - 55
      _ => raise InputError("invalid hexadecimal number")
    }
    guard digit <= maximum && number <= (maximum - digit) / 16 else {
      raise InputError("hexadecimal number exceeds limit")
    }
    number = number * 16 + digit
  }
  number
}

///|
fn http_chunks(bytes : BytesView, limit : Int32) -> HttpBody raise InputError {
  let output : Array[Byte] = []
  let mut offset = 0
  while offset < bytes.length() {
    let end = match find_bytes(bytes, b"\r\n", start=offset) {
      Some(end) => end
      None => return { data: Bytes::from_array(output), complete: false, }
    }
    guard end - offset <= 1024 else {
      raise InputError("HTTP chunk size line exceeds limit")
    }
    let line = @utf8.decode_lossy(bytes[offset:end])
    let size = hex_number(line.split(";").next().unwrap().trim(), 2147483647)
    offset = end + 2
    if size == 0 {
      let complete = bytes[offset:offset + 2] == b"\r\n" ||
        find_bytes(bytes, b"\r\n\r\n", start=offset) is Some(_)
      return { data: Bytes::from_array(output), complete, }
    }
    let available = Int32::min(size, bytes.length() - offset)
    guard available <= limit - output.length() else {
      raise InputError("HTTP body exceeds limit")
    }
    for byte in bytes[offset:offset + available] {
      output.push(byte)
    }
    if available < size {
      return { data: Bytes::from_array(output), complete: false, }
    }
    offset += size
    if offset + 2 > bytes.length() {
      return { data: Bytes::from_array(output), complete: false, }
    }
    guard bytes[offset:offset + 2] == b"\r\n" else {
      raise InputError("invalid HTTP chunk delimiter")
    }
    offset += 2
  }
  { data: Bytes::from_array(output), complete: false, }
}

///|
fn http_body(
  bytes : BytesView,
  head : HttpHead,
  eof : Bool,
  limit : Int32,
) -> HttpBody raise InputError {
  if head.code is (204 | 304) {
    return { data: b"", complete: true, }
  }
  let body = bytes[head.body_offset:]
  if head.headers.get("transfer-encoding") is Some(encoding) {
    guard ascii_lower(encoding) == "chunked" else {
      raise InputError("unsupported transfer encoding")
    }
    return http_chunks(body, limit)
  }
  if head.headers.get("content-length") is Some(length) {
    let length = decimal(length[:], 2147483647)
    let available = Int32::min(body.length(), length)
    return { data: body[:available].to_owned(), complete: available == length, }
  }
  { data: body.to_owned(), complete: eof, }
}

///|
fn http_info(
  bytes : BytesView,
  secure : Bool,
  truncated : Bool,
  max_decoded_bytes~ : Int32 = 16384,
  cancelled~ : () -> Bool = () => false,
) -> ServiceInfo raise {
  guard http_head(bytes) is Some(head) else {
    raise InputError("incomplete HTTP headers")
  }
  let body = http_body(bytes, head, true, bytes.length())
  let mut data = body.data
  if head.headers.get("content-encoding") is Some(encoding) {
    data = match ascii_lower(encoding) {
      "identity" => data
      "gzip" =>
        @gzip.decompress(data, max_output_bytes=max_decoded_bytes, cancelled~)
      "deflate" =>
        @zlib.decompress(data, max_output_bytes=max_decoded_bytes, cancelled~)
      _ => raise InputError("unsupported HTTP content encoding")
    }
  }
  {
    ..http_evidence(head, secure),
    title: html_title(@utf8.decode_lossy(data)),
    truncated: truncated || !body.complete,
  }
}

///|
fn http_evidence(head : HttpHead, secure : Bool) -> ServiceInfo {
  {
    ..service(if secure { "https" } else { "http" }),
    http_status: Some(head.code),
    server: head.headers.get("server"),
    location: head.headers.get("location"),
  }
}

///|
async fn[R : @io.BinaryReader] read_http(
  reader : R,
  max_bytes : Int32,
  on_data~ : (Bytes) -> Unit,
) -> Bytes {
  let buffer = FixedArray::make(max_bytes, b'\x00')
  let mut used = 0
  while used < max_bytes {
    let count = reader.read_into(buffer.mut_view(start=used))
    let eof = count == 0
    used += count
    let bytes = Bytes::from_array(buffer[:used].to_owned())
    if http_head(bytes) is Some(head) {
      // Retain header evidence even when body decoding later fails or times out.
      let framed = http_body(bytes, head, eof, max_bytes)
      on_data(bytes)
      if framed.complete {
        return bytes
      }
      if eof {
        raise InputError("incomplete HTTP body")
      }
    }
    if eof {
      break
    }
  }
  Bytes::from_array(buffer[:used].to_owned())
}

///|
fn html_title(text : String) -> String? {
  let lower = ascii_lower(text)
  let mut offset = 0
  while offset < lower.length() {
    guard lower[offset:].find("' | ' ' | '\t' | '\r' | '\n') &&
      lower[start:].find(">") is Some(open_end) &&
      lower[start + open_end + 1:].find(" String {
  let output = StringBuilder()
  let mut offset = 0
  while offset < text.length() {
    if text[offset] == '&' &&
      text[offset:].find(";") is Some(relative) &&
      relative <= 16 {
      let end = offset + relative
      let name = text[offset + 1:end]
      let decoded = match name {
        "amp" => Some('&')
        "lt" => Some('<')
        "gt" => Some('>')
        "quot" => Some('"')
        "apos" => Some('\'')
        "nbsp" => Some(' ')
        _ => {
          let value = try {
            if name.has_prefix("#x") || name.has_prefix("#X") {
              hex_number(name[2:], 0x10ffff)
            } else if name.has_prefix("#") {
              decimal(name[1:], 0x10ffff)
            } else {
              raise InputError("unknown entity")
            }
          } catch {
            _ => -1
          }
          if value > 0 &&
            value <= 0x10ffff &&
            !(value >= 0xd800 && value <= 0xdfff) {
            Some(value.unsafe_to_char())
          } else {
            None
          }
        }
      }
      if decoded is Some(c) {
        output.write_char(c)
        offset = end + 1
        continue
      }
    }
    let c = text.get_char(offset).unwrap()
    output.write_char(c)
    offset += if c.to_int() > 0xffff { 2 } else { 1 }
  }
  output.to_string()
}