///|
#derive(Debug, Eq)
pub(all) struct ServiceUri {
  authority : String
  host : String
  port : Int32
  resource : String
}

///|
pub fn parse_uri(uri : String) -> Result[ServiceUri, ProtocolError] {
  if !uri.has_prefix("icap://") || !safe_value(uri) {
    return Err(Malformed("expected icap:// URI", 0))
  }
  let chars = uri.to_array()
  for i = 0; i < chars.length(); i = i + 1 {
    let c = chars[i]
    if c == '%' {
      if i + 2 >= chars.length() ||
        hexadecimal(String::from_array(chars[i + 1:i + 3].to_owned())) is None {
        return Err(Malformed("malformed URI escape", i))
      }
    } else if !(c >= 'a' && c <= 'z') &&
      !(c >= 'A' && c <= 'Z') &&
      !(c >= '0' && c <= '9') &&
      !";/?:@&=+$,-_.!~*'()[]".contains(c.to_string()) {
      return Err(Malformed("character must be URI-escaped", i))
    }
  }
  for c in chars {
    if c.to_int() <= 32 || c.to_int() > 126 || c == '#' {
      return Err(Malformed("invalid URI character", 0))
    }
  }
  let mut slash = chars.length()
  for i = 7; i < chars.length(); i = i + 1 {
    if chars[i] == '/' || chars[i] == '?' {
      slash = i
      break
    }
  }
  let authority = String::from_array(chars[7:slash].to_owned())
  if authority.is_empty() || authority.contains("@") {
    return Err(Malformed("invalid authority", 7))
  }
  let resource = if slash < chars.length() {
    String::from_array(chars[slash:].to_owned())
  } else {
    "/"
  }
  let mut host = authority
  let mut port = 1344
  if authority.has_prefix("[") {
    let a = authority.to_array()
    let mut closing = -1
    for i = 1; i < a.length(); i = i + 1 {
      if a[i] == ']' {
        closing = i
        break
      }
    }
    if closing <= 1 {
      return Err(Malformed("invalid bracketed host", 7))
    }
    host = String::from_array(a[1:closing].to_owned())
    if closing + 1 < a.length() {
      if a[closing + 1] != ':' {
        return Err(Malformed("invalid host port separator", 7))
      }
      match decimal(String::from_array(a[closing + 2:].to_owned())) {
        Some(n) => port = n
        None => return Err(Malformed("invalid port", 7))
      }
    }
  } else {
    let parts = authority.split(":").map(s => s.to_owned()).to_array()
    if parts.length() > 2 || parts[0].is_empty() {
      return Err(Malformed("IPv6 requires brackets", 7))
    }
    host = parts[0]
    if parts.length() == 2 {
      match decimal(parts[1]) {
        Some(n) => port = n
        None => return Err(Malformed("invalid port", 7))
      }
    }
  }
  if port < 1 || port > 65535 {
    return Err(Malformed("port outside 1..65535", 7))
  }
  Ok({ authority, host, port, resource, })
}