///|
priv struct BitReader {
  bytes : BytesView
  mut byte_pos : Int
  mut bit_buf : UInt
  mut bit_count : Int
}

///|
fn BitReader::new(bytes : BytesView) -> BitReader {
  { bytes, byte_pos: 0, bit_buf: 0, bit_count: 0 }
}

///|
fn BitReader::ensure_bits(self : BitReader, count : Int) -> Unit raise ZipError {
  if count < 0 {
    raise OutOfBounds(offset=self.byte_pos)
  }
  while self.bit_count < count {
    if self.byte_pos >= self.bytes.length() || self.byte_pos < 0 {
      raise OutOfBounds(offset=self.byte_pos)
    }
    let byte = self.bytes[self.byte_pos].to_uint()
    self.bit_buf = self.bit_buf | (byte << self.bit_count)
    self.bit_count = self.bit_count + 8
    self.byte_pos = self.byte_pos + 1
  }
}

///|
fn BitReader::read_bits(self : BitReader, count : Int) -> UInt raise ZipError {
  self.ensure_bits(count)
  let mask = bit_mask(count)
  let value = self.bit_buf & mask
  self.bit_buf = self.bit_buf >> count
  self.bit_count = self.bit_count - count
  value
}

///|
fn BitReader::drop_bits(self : BitReader, count : Int) -> Unit raise ZipError {
  self.ensure_bits(count)
  self.bit_buf = self.bit_buf >> count
  self.bit_count = self.bit_count - count
}

///|
/// Fill the bit buffer with up to `count` bits and return them without
/// consuming any. Near the end of input fewer bits may remain; missing high
/// bits are zero-padded, and `self.bit_count` reflects how many bits are
/// actually available. `count` must be in `0..=15`.
fn BitReader::peek_bits(self : BitReader, count : Int) -> UInt {
  while self.bit_count < count && self.byte_pos < self.bytes.length() {
    let byte = self.bytes[self.byte_pos].to_uint()
    self.bit_buf = self.bit_buf | (byte << self.bit_count)
    self.bit_count = self.bit_count + 8
    self.byte_pos = self.byte_pos + 1
  }
  self.bit_buf & bit_mask(count)
}

///|
fn BitReader::align_byte(self : BitReader) -> Unit raise ZipError {
  let drop = self.bit_count % 8
  if drop != 0 {
    self.drop_bits(drop)
  }
}

///|
fn BitReader::read_byte(self : BitReader) -> Byte raise ZipError {
  self.read_bits(8).to_byte()
}

///|
/// Mask of the low `count` bits. `count` must be in `0..=31`; callers only
/// ever pass at most 16 (stored-block lengths) and `max_bits <= 15` for
/// huffman codes.
fn bit_mask(count : Int) -> UInt {
  (1U << count) - 1
}

///|
fn reverse_bits(value : UInt, bits : Int) -> UInt {
  let mut v = value
  let mut result : UInt = 0
  for _ in 0..> 1
  }
  result
}

///|
let length_base : Array[Int] = [
  3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83,
  99, 115, 131, 163, 195, 227, 258,
]

///|
let length_extra : Array[Int] = [
  0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5,
  5, 0,
]

///|
let dist_base : Array[Int] = [
  1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769,
  1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577,
]

///|
let dist_extra : Array[Int] = [
  0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
  12, 12, 13, 13,
]

///|
fn length_to_symbol(length : Int) -> (Int, Int, Int) raise ZipError {
  if length < 3 || length > 258 {
    raise UnsupportedFeature(msg="invalid match length")
  }
  for idx in 0.. (Int, Int, Int) raise ZipError {
  if distance <= 0 || distance > 32768 {
    raise UnsupportedFeature(msg="invalid match distance")
  }
  for idx in 0.. Int {
  let b0 = bytes[pos].to_int()
  let b1 = bytes[pos + 1].to_int()
  let b2 = bytes[pos + 2].to_int()
  let hash = (b0 << 10) ^ (b1 << 5) ^ b2
  hash & ((1 << 15) - 1)
}

///|
fn insert_position(
  bytes : BytesView,
  pos : Int,
  head : Array[Int],
  prev : Array[Int],
) -> Unit {
  if pos + 2 >= bytes.length() {
    return
  }
  let h = hash3(bytes, pos)
  prev[pos] = head[h]
  head[h] = pos
}

///|
fn find_match(
  bytes : BytesView,
  pos : Int,
  head : Array[Int],
  prev : Array[Int],
) -> (Int, Int) {
  let len = bytes.length()
  if pos + 3 > len {
    return (0, 0)
  }
  let max_len = if len - pos < 258 { len - pos } else { 258 }
  let h = hash3(bytes, pos)
  let mut candidate = head[h]
  let mut best_len = 0
  let mut best_dist = 0
  let mut chain_count = 0
  for state = true {
    if !state {
      break
    }
    if candidate < 0 || chain_count >= 128 {
      continue false
    }
    let dist = pos - candidate
    if dist > 32768 {
      continue false
    }
    let mut l = 0
    while l < max_len && bytes[candidate + l] == bytes[pos + l] {
      l = l + 1
    }
    if l >= 3 && l > best_len {
      best_len = l
      best_dist = dist
      if l == max_len {
        continue false
      }
    }
    candidate = prev[candidate]
    chain_count = chain_count + 1
    continue true
  }
  (best_len, best_dist)
}

///|
priv struct HuffmanTable {
  max_bits : Int
  sym : Array[Int]
  len : Array[Int]
}

///|
fn build_huffman(lengths : ArrayView[Int]) -> HuffmanTable raise ZipError {
  let mut max_bits = 0
  for len in lengths {
    if len < 0 || len > 15 {
      raise UnsupportedFeature(msg="invalid huffman length")
    }
    if len > max_bits {
      max_bits = len
    }
  }
  if max_bits == 0 {
    raise UnsupportedFeature(msg="empty huffman table")
  }
  let counts : Array[Int] = Array::make(max_bits + 1, 0)
  for len in lengths {
    if len > 0 {
      counts[len] = counts[len] + 1
    }
  }
  // Reject oversubscribed length sets (Kraft inequality violated). The flat
  // lookup table would otherwise let colliding canonical codes overwrite one
  // another and silently "decode" malformed input that a strict decoder
  // rejects; zlib performs the same validation. Incomplete sets stay
  // accepted, matching the historical decoder.
  let mut remaining = 1
  for bits in 1..<=max_bits {
    remaining = (remaining << 1) - counts[bits]
    if remaining < 0 {
      raise UnsupportedFeature(msg="oversubscribed huffman table")
    }
  }
  let next_code : Array[Int] = Array::make(max_bits + 1, 0)
  let mut code = 0
  for bits in 1..<=max_bits {
    code = (code + counts[bits - 1]) << 1
    next_code[bits] = code
  }
  let size = 1 << max_bits
  let sym : Array[Int] = Array::make(size, -1)
  let len_table : Array[Int] = Array::make(size, 0)
  for symbol, length in lengths {
    if length == 0 {
      continue
    }
    let curr = next_code[length]
    next_code[length] = curr + 1
    let rev = reverse_bits(curr.reinterpret_as_uint(), length).reinterpret_as_int()
    let fill = 1 << (max_bits - length)
    for i in 0.. Int raise ZipError {
  let idx = reader.peek_bits(table.max_bits).reinterpret_as_int()
  let len = table.len[idx]
  if len == 0 || len > reader.bit_count {
    if reader.bit_count < table.max_bits {
      // Input ended mid-code: the bit-serial decoder would have failed to
      // read the next bit here.
      raise OutOfBounds(offset=reader.byte_pos)
    }
    raise UnsupportedFeature(msg="invalid huffman code")
  }
  reader.drop_bits(len)
  table.sym[idx]
}

///|
fn fixed_literal_table() -> HuffmanTable raise ZipError {
  let lengths : Array[Int] = []
  for i in 0..<=287 {
    if i <= 143 {
      lengths.push(8)
    } else if i <= 255 {
      lengths.push(9)
    } else if i <= 279 {
      lengths.push(7)
    } else {
      lengths.push(8)
    }
  }
  build_huffman(lengths)
}

///|
fn fixed_distance_table() -> HuffmanTable raise ZipError {
  let lengths : Array[Int] = []
  for _ in 0..<=31 {
    lengths.push(5)
  }
  build_huffman(lengths)
}

///|
fn read_dynamic_tables(
  reader : BitReader,
) -> (HuffmanTable, HuffmanTable) raise ZipError {
  let hlit = reader.read_bits(5).reinterpret_as_int() + 257
  let hdist = reader.read_bits(5).reinterpret_as_int() + 1
  let hclen = reader.read_bits(4).reinterpret_as_int() + 4
  let order = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]
  let code_lengths : Array[Int] = Array::make(19, 0)
  for i in 0.. Unit raise ZipError {
  for state = true {
    if !state {
      break
    }
    let symbol = decode_symbol(reader, lit_table)
    if symbol < 256 {
      if out.length() >= max_output {
        raise OutputLimitExceeded(limit=max_output)
      }
      out.push(symbol.to_byte())
      continue true
    }
    if symbol == 256 {
      continue false
    }
    let length_idx = symbol - 257
    if length_idx < 0 || length_idx >= length_base.length() {
      raise UnsupportedFeature(msg="invalid length symbol")
    }
    let extra_len = length_extra[length_idx]
    let length = length_base[length_idx] +
      reader.read_bits(extra_len).reinterpret_as_int()
    let dist_symbol = decode_symbol(reader, dist_table)
    if dist_symbol < 0 || dist_symbol >= dist_base.length() {
      raise UnsupportedFeature(msg="invalid distance symbol")
    }
    let dist = dist_base[dist_symbol] +
      reader.read_bits(dist_extra[dist_symbol]).reinterpret_as_int()
    if dist <= 0 || dist > out.length() {
      raise UnsupportedFeature(msg="invalid back-reference distance")
    }
    if length > max_output - out.length() {
      raise OutputLimitExceeded(limit=max_output)
    }
    for _ in 0.. BitWriter {
  { bit_buf: 0, bit_count: 0, out: [] }
}

///|
fn BitWriter::write_bits(
  self : BitWriter,
  value : Int,
  count : Int,
) -> Unit raise ZipError {
  if count < 0 {
    raise UnsupportedFeature(msg="negative bit count")
  }
  for i in 0..> i) & 1
    self.bit_buf = self.bit_buf | (bit.reinterpret_as_uint() << self.bit_count)
    self.bit_count = self.bit_count + 1
    if self.bit_count == 8 {
      self.out.push(self.bit_buf.to_byte())
      self.bit_buf = 0
      self.bit_count = 0
    }
  }
}

///|
fn BitWriter::finish(self : BitWriter) -> Bytes {
  if self.bit_count > 0 {
    self.out.push(self.bit_buf.to_byte())
  }
  Bytes::from_array(self.out)
}

///|
fn fixed_literal_code(symbol : Int) -> (Int, Int) raise ZipError {
  if symbol < 0 || symbol > 287 {
    raise UnsupportedFeature(msg="invalid fixed literal symbol")
  }
  if symbol <= 143 {
    (symbol + 0x30, 8)
  } else if symbol <= 255 {
    (symbol - 144 + 0x190, 9)
  } else if symbol <= 279 {
    (symbol - 256, 7)
  } else {
    (symbol - 280 + 0xC0, 8)
  }
}

///|
fn deflate_encode(bytes : BytesView) -> Bytes raise ZipError {
  let writer = BitWriter::new()
  writer.write_bits(1, 1)
  writer.write_bits(1, 2)
  let len = bytes.length()
  let head : Array[Int] = Array::make(1 << 15, -1)
  let prev : Array[Int] = Array::make(len, -1)
  let mut i = 0
  for state = true {
    if !state {
      break
    }
    if i >= len {
      continue false
    }
    let (match_len, match_dist) = find_match(bytes, i, head, prev)
    if match_len >= 3 {
      let (len_sym, len_extra, len_value) = length_to_symbol(match_len)
      let (len_code, len_bits) = fixed_literal_code(len_sym)
      let len_rev = reverse_bits(len_code.reinterpret_as_uint(), len_bits).reinterpret_as_int()
      writer.write_bits(len_rev, len_bits)
      if len_extra > 0 {
        writer.write_bits(len_value, len_extra)
      }
      let (dist_sym, dist_extra, dist_value) = distance_to_symbol(match_dist)
      let dist_rev = reverse_bits(dist_sym.reinterpret_as_uint(), 5).reinterpret_as_int()
      writer.write_bits(dist_rev, 5)
      if dist_extra > 0 {
        writer.write_bits(dist_value, dist_extra)
      }
      for j in 0.. Bytes raise ZipError {
  let reader = BitReader::new(bytes)
  let out : Array[Byte] = []
  for state = false {
    if state {
      break
    }
    let bfinal = reader.read_bits(1)
    let btype = reader.read_bits(2)
    match btype {
      0 => {
        reader.align_byte()
        let len = reader.read_bits(16).reinterpret_as_int()
        let nlen = reader.read_bits(16)
        if (len.reinterpret_as_uint() ^ nlen) != 0xFFFF {
          raise UnsupportedFeature(msg="invalid stored block length")
        }
        if len > max_output - out.length() {
          raise OutputLimitExceeded(limit=max_output)
        }
        for _ in 0.. {
        let lit = fixed_literal_table()
        let dist = fixed_distance_table()
        decode_huffman_block(reader, lit, dist, out, max_output~)
      }
      2 => {
        let (lit, dist) = read_dynamic_tables(reader)
        decode_huffman_block(reader, lit, dist, out, max_output~)
      }
      _ => raise UnsupportedFeature(msg="invalid deflate block type")
    }
    continue bfinal == 1
  }
  Bytes::from_array(out)
}