///|
/// Parse JSON text. Duplicate keys in an object are an error.
fn parse_json(text : StringView) -> Json raise ProtocolError {
  @json.parse(text, reject_duplicate_keys=true, preserve_number_repr=true) catch {
    err => raise InvalidJson(detail=err.to_string())
  }
}

///|
/// The integer that the JSON number `text` denotes exactly, or `None` when it has a
/// fraction or does not fit `Int64` or `UInt64`. The digits decide, and not the
/// nearest double: `1.0000000000000001` is not an integer, and `1.5e1` is 15.
fn exact_integer(text : String) -> HubValue? {
  let negative = text.has_prefix("-")
  // The digits with no leading zeros, and the power of ten that scales them.
  let digits : Array[Char] = []
  let mut scale = 0L
  let mut in_fraction = false
  let mut in_exponent = false
  let mut exponent = 0L
  let mut exponent_negative = false
  for char in text {
    match char {
      '.' => in_fraction = true
      'e' | 'E' => in_exponent = true
      '-' => if in_exponent { exponent_negative = true }
      '0'..<='9' if in_exponent =>
        // No text has this many digits, so a larger exponent gives the same result.
        if exponent < 1000000000000L {
          exponent = exponent * 10L + (char.to_int() - '0'.to_int()).to_int64()
        }
      '0'..<='9' => {
        if in_fraction {
          scale -= 1L
        }
        if char != '0' || !digits.is_empty() {
          digits.push(char)
        }
      }
      _ => ()
    }
  }
  scale += if exponent_negative { -exponent } else { exponent }
  while digits.last() is Some('0') {
    ignore(digits.pop())
    scale += 1L
  }
  if digits.is_empty() {
    return Some(Int(0L))
  }
  // 2^64 has 20 digits.
  guard scale >= 0L && digits.length().to_int64() + scale <= 20L else {
    return None
  }
  for _ in 0L.. 9223372036854775807UL {
        UInt(magnitude)
      } else {
        Int(magnitude.reinterpret_as_int64())
      },
    )
  }
  guard magnitude <= 9223372036854775808UL else { return None }
  Some(Int(-(magnitude - 1UL).reinterpret_as_int64() - 1L))
}

///|
/// The payload value of a JSON value. A number that is exactly an integer, also with
/// an exponent, gives `Int`, or `UInt` above the range of `Int64`. Another number
/// gives `Double`, so a `Double` from JSON is never an exact 64-bit integer. A JSON string
/// stays a string: a codec reads Base64 bytes and timestamps from it.
pub fn HubValue::from_json(json : Json) -> HubValue raise ProtocolError {
  match json {
    Null => Null
    True => Bool(true)
    False => Bool(false)
    Number(value, repr~) => number_value(value, repr)
    String(text) => String(text)
    Array(items) => {
      let values = []
      for item in items {
        values.push(HubValue::from_json(item))
      }
      HubValue::array(values)
    }
    Object(map) => {
      let entries = []
      for key, value in map {
        entries.push((key, HubValue::from_json(value)))
      }
      // The parser rejects duplicate keys, so the map has unique keys.
      Map(
        HubMap::new(entries) catch {
          _ => raise InvalidJson(detail="duplicate key")
        },
      )
    }
  }
}

///|
fn number_value(value : Double, repr : String?) -> HubValue raise ProtocolError {
  let text = repr.unwrap_or(value.to_string())
  if exact_integer(text) is Some(integer) {
    return integer
  }
  Double(
    FiniteDouble::parse(value) catch {
      _ => raise NumberOutOfRange(text~)
    },
  )
}

///|
/// The JSON value of a payload value: integers with their exact digits, bytes as
/// Base64 text with padding, and timestamps as ISO 8601 text in UTC.
pub fn HubValue::to_json(self : HubValue) -> Json {
  match self {
    Null => Json::null()
    Bool(flag) => Json::boolean(flag)
    Int(number) => Json::number(number.to_double(), repr=number.to_string())
    UInt(number) => Json::number(number.to_double(), repr=number.to_string())
    Double(number) => Json::number(number.value())
    String(text) => Json::string(text)
    Bytes(data) => Json::string(@base64.encode(data))
    Timestamp(instant) => Json::string(instant.to_string())
    Array(items) =>
      Json::array(items.iter().map(item => item.to_json()).collect())
    Map(map) => {
      let object : Map[String, Json] = Map([])
      for entry in map.iter() {
        object[entry.0] = entry.1.to_json()
      }
      Json::object(object)
    }
  }
}

///|
/// Read a payload value from JSON text.
pub fn HubValue::parse_json(text : StringView) -> HubValue raise ProtocolError {
  HubValue::from_json(parse_json(text))
}

///|
/// The compact JSON text of a payload value.
pub fn HubValue::to_json_text(self : HubValue) -> String {
  self.to_json().stringify()
}