Skip to content

Instantly share code, notes, and snippets.

@rflechner
Last active December 9, 2016 14:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rflechner/8092493473c6088c16ee178096a77e0a to your computer and use it in GitHub Desktop.
Save rflechner/8092493473c6088c16ee178096a77e0a to your computer and use it in GitHub Desktop.
Encode and decode url algorithm
let toHex (c:char) = Convert.ToInt32(c) |> fun i -> i.ToString("X")
let encode s =
let parts = s |> Seq.map (fun c -> "%" + (c |> toHex))
String.Join("", parts)
let (|HexaChar|_|) (s:char list) =
if s.Length > 0 && s.Head = '%' then
let chars = s |> Seq.skip 1 |> Seq.take 2 |> Array.ofSeq
let h = new String(chars)
let num = Convert.ToInt32(h, 16)
let tail = s |> Seq.skip (chars.Length+1) |> List.ofSeq
Some ((Convert.ToChar num), tail)
else
None
let toChars (s:string) =
[for i in [0..s.Length] -> s.[i]]
let urlDecode (text:string) =
let rec decode s acc =
match s with
| HexaChar (c, t) -> decode t (c :: acc)
| c :: t -> decode t (c :: acc)
| [] -> new string(acc |> List.rev |> Array.ofList)
decode (text |> toChars) []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment