From fba9b0fbfe561e37ff6ca205e4b9315b9e207c25 Mon Sep 17 00:00:00 2001 From: Ramakrishnan Muthukrishnan <ram@rkrishnan.org> Date: Wed, 4 Feb 2015 05:26:12 +0530 Subject: [PATCH] parser for strings --- src/Bencode.hs | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/Bencode.hs diff --git a/src/Bencode.hs b/src/Bencode.hs new file mode 100644 index 0000000..951f4f1 --- /dev/null +++ b/src/Bencode.hs @@ -0,0 +1,38 @@ +module Bencode where + +-- import qualified Data.ByteString.Lazy as BL +import qualified Data.ByteString.Char8 as BC +import qualified Data.Map as M +import qualified Text.Parsec.ByteString as ParsecBS +import Text.ParserCombinators.Parsec +import Control.Applicative ((<*)) +import Data.Functor + + + +data BVal = + Bint Integer + | Bstr BC.ByteString + | Blist [BVal] + | Bdict (M.Map BVal BVal) + deriving (Ord, Eq) + +-- | parse strings +-- +-- >>> parse bencStr "Bstr" (BC.pack "4:spam") +-- Right "spam" +-- >>> parse bencStr "Bstr" (BC.pack "0:") +-- Right "" +-- >>> parse bencStr "Bstr" (BC.pack "0:hello") +-- Right "" +bencStr :: ParsecBS.Parser BC.ByteString +bencStr = do _ <- spaces + ds <- many1 digit <* char ':' + s <- count (read ds) anyChar + return (BC.pack s) + +bencParser :: ParsecBS.Parser BVal +bencParser = Bstr <$> bencStr + +decode :: BC.ByteString -> Either ParseError BVal +decode = parse bencParser "BVal" -- 2.45.2