From: Ramakrishnan Muthukrishnan Date: Tue, 3 Feb 2015 23:56:12 +0000 (+0530) Subject: parser for strings X-Git-Url: https://git.rkrishnan.org/pf/content/en/seg/priv/banana.xhtml?a=commitdiff_plain;h=fba9b0fbfe561e37ff6ca205e4b9315b9e207c25;p=functorrent.git parser for strings --- 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"