From: Ramakrishnan Muthukrishnan Date: Thu, 12 Feb 2015 12:12:21 +0000 (+0530) Subject: encode with tests X-Git-Url: https://git.rkrishnan.org/pf/content/en/footer/frontends/class-simplejson.JSONDecoder.html?a=commitdiff_plain;h=c20696b82bd144f85c363a11d64a3aaea5844f2f;p=functorrent.git encode with tests --- diff --git a/src/Bencode.hs b/src/Bencode.hs index 62627a6..16e4a2b 100644 --- a/src/Bencode.hs +++ b/src/Bencode.hs @@ -121,7 +121,18 @@ decode = parse bencVal "BVal" -- "i0e" -- >>> encode (Bint 42) -- "i42e" +-- >>> encode (Blist [(Bstr (BC.pack "spam")), (Bstr (BC.pack "eggs"))]) +-- "l4:spam4:eggse" +-- >>> encode (Blist []) +-- "le" +-- >>> encode (Bdict (M.fromList [(Bstr $ BC.pack "spam", Bstr $ BC.pack "eggs")])) +-- "d4:spam4:eggse" encode :: BVal -> String encode (Bstr bs) = let s = BC.unpack bs in show (length s) ++ ":" ++ s encode (Bint i) = "i" ++ show i ++ "e" +encode (Blist xs) = "l" ++ encodeList xs ++ "e" + where encodeList [] = "" + encodeList (x:xs) = encode x ++ encodeList xs +encode (Bdict d) = "d" ++ encodeDict d ++ "e" + where encodeDict m = concat [encode k ++ encode (m M.! k) | k <- M.keys m]