Skip to content

Instantly share code, notes, and snippets.

@kavan-mevada
Created January 19, 2020 11:12
Show Gist options
  • Save kavan-mevada/5d9fca9d98bcad79a3621a9125606daf to your computer and use it in GitHub Desktop.
Save kavan-mevada/5d9fca9d98bcad79a3621a9125606daf to your computer and use it in GitHub Desktop.
// http_URL = "http:" "//" host [ ":" port ] [ abs_path [ "?" query ]]
//
// Usage:
// ----------------------------------------------
// val url = URL("http://abc.com:80/smith/home.html?key=value&key2=value2")
// println("${url.protocol} -- ${url.host} -- ${url.port} -- ${url.path} -- ${url.query}")
// ---------------------------------------------
class URL(url: String){
var protocol = ""
var host = ""
var port = ""
var path = ""
var query = ""
var slashCount = 0
var colonCount = 0
var qustionCount = 0
init {
for (i in url.indices) {
val char = url[i]
val decimal = char.decimal
when (decimal) {
47 /* / */ -> slashCount++
58 /* : */ -> colonCount++
63 /* ? */ -> qustionCount++
}
when {
slashCount==0 && colonCount==0 && qustionCount==0 -> if (decimal.isText) protocol+=char
slashCount==2 && colonCount==1 && qustionCount==0 -> if (decimal.isAllowed(Type.HOST)) host+=char
slashCount==2 && colonCount==2 && qustionCount==0 -> if (decimal.isAllowed(Type.PORT)) port+=char
slashCount>2 && qustionCount==0 -> if (decimal.isAllowed(Type.PATH)) path+=char
slashCount>2 && qustionCount==1 -> if (decimal.isAllowed(Type.QUERY)) query+=char
}
}
}
enum class Type { HOST, PORT, PATH, QUERY }
val Char.decimal get() = this - '0' + 48
fun Int.isAllowed(type: Type): Boolean {
return when (type) {
Type.HOST -> (this.isText|| this==46)
Type.PORT -> this.isNumber
Type.PATH -> (this.isText || this.isNumber || this==46 || this==47 || this==95)
Type.QUERY -> (this.isText || this.isNumber || this==61 || this==38)
}
}
val Int.isText get() = this in 97..122 || this in 65..90
val Int.isNumber get() = this in 48..57
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment