RosettaCodeData/Task/URL-encoding/M2000-Interpreter/url-encoding.m2000

70 lines
2.5 KiB
Plaintext

Module Checkit {
Function decodeUrl$(a$) {
DIM a$()
a$()=Piece$(a$, "%")
if len(a$())=1 then =str$(a$):exit
k=each(a$(),2)
acc$=str$(a$(0))
While k {
acc$+=str$(Chr$(Eval("0x"+left$(a$(k^),2)))+Mid$(a$(k^),3))
}
=string$(acc$ as utf8dec)
}
Group Parse$ {
all$, c=1
tc$=""
Enum UrlType {None=0, RFC3986, HTML5}
variation
TypeData=("","-._~","-._*")
Function Next {
.tc$<=mid$(.all$,.c,1)
.c++
=.tc$<>""
}
Value {
=.tc$
}
Function DecodeOne$ {
if .tc$="" then exit
if .tc$ ~"[A-Za-z0-9]" then =.tc$ : exit
If .tc$=" " Then =if$(.variation=.HTML5->"+","%20") :exit
if instr(.TypeData#val$(.variation),.tc$)>0 then =.tc$ :exit
="%"+hex$(asc(.tc$), 1)
}
Function Decode$ {
acc$=""
.c<=1
While .Next() {
acc$+=.DecodeOne$()
}
=acc$
}
Set () {
\\ using optional argument
var=.None
Read a$, ? var
a$=chr$(string$(a$ as utf8enc))
.variation<=var
.all$<=a$
.c<=1
}
}
\\ MAIN
Parse$()="http://foo bar/"
Print Quote$(Parse.Decode$())
Parse.variation=Parse.HTML5
Print Quote$(Parse.Decode$())
Parse.variation=Parse.RFC3986
Print Quote$(Parse.Decode$())
Parse$(Parse.RFC3986) ={mailto:"Irma User" <irma.user@mail.com>}
Print Quote$(Parse.Decode$())
Parse$(Parse.RFC3986) ={http://foo.bar.com/~user-name/_subdir/*~.html}
m=each(Parse.UrlType)
while m {
Parse.variation=eval(m)
Print Quote$(Parse.Decode$())
Print decodeUrl$(Parse.Decode$())
}
}
CheckIt