///|
// The caller has checked the full header or descriptor table before reading.
fn read_word(bytes : Bytes, pos : Int32, order : Endianness) -> UInt32 {
  let a = bytes[pos].to_uint()
  let b = bytes[pos + 1].to_uint()
  let c = bytes[pos + 2].to_uint()
  let d = bytes[pos + 3].to_uint()
  match order {
    Little => a | (b << 8) | (c << 16) | (d << 24)
    Big => (a << 24) | (b << 16) | (c << 8) | d
  }
}

///|
fn check_table(
  table : String,
  offset : UInt32,
  byte_len : UInt64,
  file_len : Int32,
) -> Unit raise MoError {
  let start = offset.to_uint64()
  if byte_len != 0 && (start < 28 || start + byte_len > file_len.to_uint64()) {
    raise InvalidTableRange(table~, offset=start, byte_len~, file_len~)
  }
}

///|
fn read_header(bytes : Bytes) -> MoHeader raise MoError {
  let file_len = bytes.length()
  if file_len < 28 {
    raise TruncatedHeader(actual_len=file_len)
  }
  let order = match read_word(bytes, 0, Little) {
    0x950412DE => Little
    0xDE120495 => Big
    magic => raise InvalidMagic(magic~)
  }
  let revision = read_word(bytes, 4, order)
  if revision != 0 {
    raise UnsupportedRevision(major=revision >> 16, minor=revision & 0xFFFF)
  }
  let header : MoHeader = {
    endianness: order,
    major_revision: 0,
    minor_revision: 0,
    num_strings: read_word(bytes, 8, order),
    orig_tab_offset: read_word(bytes, 12, order),
    trans_tab_offset: read_word(bytes, 16, order),
    hash_tab_size: read_word(bytes, 20, order),
    hash_tab_offset: read_word(bytes, 24, order),
  }
  let size = header.num_strings.to_uint64() * 8
  check_table("original", header.orig_tab_offset, size, file_len)
  check_table("translation", header.trans_tab_offset, size, file_len)
  check_table(
    "hash",
    header.hash_tab_offset,
    header.hash_tab_size.to_uint64() * 4,
    file_len,
  )
  header
}

///|
priv enum StringTable {
  Original
  Translation
}

///|
// index is a row of the already range-checked table in header.
fn read_string(
  bytes : Bytes,
  header : MoHeader,
  table : StringTable,
  index : Int32,
) -> BytesView raise MoError {
  let (name, base) = match table {
    Original => ("original", header.orig_tab_offset)
    Translation => ("translation", header.trans_tab_offset)
  }
  let descriptor = base.to_uint64() + 8 * index.to_uint64()
  let length = read_word(bytes, descriptor.to_int(), header.endianness).to_uint64()
  let offset = read_word(bytes, (descriptor + 4).to_int(), header.endianness).to_uint64()
  let end = offset + length
  if offset < 28 || end >= bytes.length().to_uint64() {
    raise OffsetOutOfBounds(
      table=name,
      index~,
      offset~,
      length~,
      file_len=bytes.length(),
    )
  }
  if bytes[end.to_int()] != 0 {
    raise MissingNulTerminator(table=name, index~, expected_nul_at=end)
  }
  bytes[offset.to_int():end.to_int()]
}