From c20696b82bd144f85c363a11d64a3aaea5844f2f Mon Sep 17 00:00:00 2001 From: Ramakrishnan Muthukrishnan <ram@rkrishnan.org> Date: Thu, 12 Feb 2015 17:42:21 +0530 Subject: [PATCH] encode with tests --- src/Bencode.hs | 11 +++++++++++ 1 file changed, 11 insertions(+) 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] -- 2.45.2