Punycode - encoding labels in Internationalized Domain Names

Share your advanced PureBasic knowledge/code with the community.
dige
Addict
Addict
Posts: 1254
Joined: Wed Apr 30, 2003 8:15 am
Location: Germany
Contact:

Punycode - encoding labels in Internationalized Domain Names

Post by dige »

Punycode represent Unicode with the limited character subset of ASCII supported by the Domain Name System.
For example: an email to abc@Café.org need to be encoded to: abc@xn--Caf-dma.org

What else do you need is:

- idna.dll -> http://xise.nl/mirc/idna.zip
- idna.lib -> http://www.purebasic.fr/german/viewtopi ... 87#p336881

The idna.zip includes also the dll source: "idna.c", if someone would translate it to PB, would be fine! :D

Code: Select all

; Thanks to edel and ts-soft

Import "idna.lib"
  decode(a, b, c, d, e, f)
  encode(a, b, c, d, e, f)
EndImport

dummy.s = "abc@Café.org"

Procedure.s PunyCode (txt.s, flags = 0) ; 0 - Endcode, 1 - Decode
  Protected *mem, n = Len(txt)
  
  If n > 0
    
    ; Use 4x memory size, coz encoding will inflate the string
    *mem = AllocateMemory(n*4)
    PokeS(*mem, txt)
    
    If flags
      decode(0, 0, *mem, 0, 0, 0) 
    Else
      encode(0, 0, *mem, 0, 0, 0) 
    EndIf
    
    txt = PeekS(*mem)
    FreeMemory(*mem)
  EndIf
  
  ProcedureReturn txt
EndProcedure

Procedure.s EmailEncode (txt.s)
  Protected email_name.s, email_domain.s
  
  ; if email, encode only the host part
  If FindString(txt, "@", 2)
    email_name = StringField(txt, 1, "@")
    txt = StringField(txt, 2, "@")
    email_domain = GetExtensionPart(txt)
    txt = Mid(txt, 1, Len(txt) - Len(email_domain) - 1)
  EndIf
  
  txt = PunyCode(txt)
  
  If email_name <> ""
    txt = email_name + "@" + txt + "." + email_domain
  EndIf
  
  ProcedureReturn txt
EndProcedure

Debug EmailEncode(dummy)
"Daddy, I'll run faster, then it is not so far..."