From f53654db41f602ae76c0a9f9d7657c95807dc306 Mon Sep 17 00:00:00 2001
From: Ramakrishnan Muthukrishnan <ram@rkrishnan.org>
Date: Sun, 15 Feb 2015 13:43:02 +0530
Subject: [PATCH] urlencoding: ByteString -> String

---
 src/Tracker.hs | 24 +++++++++++++++++++-----
 1 file changed, 19 insertions(+), 5 deletions(-)

diff --git a/src/Tracker.hs b/src/Tracker.hs
index 57b813d..75c3a00 100644
--- a/src/Tracker.hs
+++ b/src/Tracker.hs
@@ -12,13 +12,27 @@ splitN :: Int -> BC.ByteString -> [BC.ByteString]
 splitN n bs | BC.null bs = []
             | otherwise = (BC.take n bs) : splitN n (BC.drop n bs)
 
+-- | urlEncode
+--
+-- >>> urlEncode $ BC.pack "123456789abcdef123456789abcdef123456789a"
+-- "%124Vx%9a%bc%de%f1%23Eg%89%ab%cd%ef%124Vx%9a"
 urlEncode :: BC.ByteString -> String
-urlEncode bs = let bss = splitN 2 bs
-                   chars = map (chr . read . ("0x" ++) . BC.unpack)  bss
-               in
-                HB.urlEncode chars
-
+urlEncode bs = concatMap (encode . BC.unpack) (splitN 2 bs)
+  where encode b@(c1 : c2 : []) = let c =  chr (read ("0x" ++ b))
+                                  in
+                                   escape c c1 c2
+        encode _ = ""
+        escape i c1 c2 | isAsciiUpper i ||
+                         isAsciiLower i ||
+                         isDigit i ||
+                         i == '-' ||
+                         i == '_' ||
+                         i == '.' ||
+                         i == '~'
+                         = [i]
+                       | otherwise = "%" ++ [c1] ++ [c2]
 
+-- (chr . read . ("0x" ++) . BC.unpack)
 -- connect :: Url -> String -> IO (Benc.BVal)
 -- connect url infoHash = case (parseUrl url) of
 --                         Nothing -> putStrLn "invalid tracker URL"
-- 
2.45.2