Commits

Anonymous committed 049674b

+ urlencode

  • Participants
  • Parent commits bc8b4e5

Comments (0)

Files changed (1)

File src/cd_Strings.ml

         value split : (char -> bool) -> string -> list string;
         value decode_hex_opt : char -> option int;
         value urldecode : string -> string;
+        value urlencode : string -> string;
         value concat_array : string -> array string -> string;
         value explode : string -> list char;
         value compare_nocase_latin1 : string -> string -> int;
         ;
 
 
+        value hex_digits = "0123456789ABCDEF"
+        ;
+
+        value urlencode s =
+          let len = String.length s in
+          let buf = Buffer.create len in
+          let out ch =
+            Buffer.add_char buf ch
+          in
+          let out_esc ch =
+            let c = Char.code ch in
+            ( out '%'
+            ; out hex_digits.[c lsr 4]
+            ; out hex_digits.[c land 0x0F]
+            )
+          in
+          let rec loop i =
+            if i = len
+            then Buffer.contents buf
+            else
+              (
+                match s.[i] with
+                [   'a' .. 'z'
+                  | 'A' .. 'Z'
+                  | '-' | '.' | '_' | '~'
+                  as ch
+                    ->
+                      out ch
+                | ch ->
+                      out_esc ch
+                ]
+              ;
+                loop (i + 1)
+              )
+          in
+            loop 0
+        ;
+
+
         (* todo: more effective implementation *)
 
         value concat_array sep str_arr =