import Data.ByteString (ByteString, length, concat)
import Data.ByteString.Char8 (unpack, pack)
+import Data.Char (isLetter, isNumber, isPrint, isAscii)
import Data.Map.Strict (Map, fromList, toList)
import Text.ParserCombinators.Parsec
import qualified Text.Parsec.ByteString as ParsecBS
| Bdict (Map String BVal)
deriving (Ord, Eq, Show)
+genNonEmptyString :: Gen String
+genNonEmptyString = arbitrary `suchThat` (\s -> ((s /= "") &&
+ (all isAscii s) &&
+ (all isLetter s)))
+
instance Arbitrary ByteString where
arbitrary = pack <$> arbitrary
bval n = oneof [ Bint <$> arbitrary
, Bstr <$> arbitrary
, Blist <$> vectorOf n (bval (n `div` 4))
- , do keys <- vectorOf n arbitrary
+ , do keys <- vectorOf n genNonEmptyString
vals <- vectorOf n (bval (n `div` 4))
return $ Bdict $ fromList $ zip keys vals ]
-- Right (fromList [("publisher",Bstr "bob"),("publisher-webpage",Bstr "www.example.com"),("publisher.location",Bstr "home")])
bencDict :: ParsecBS.Parser (Map String BVal)
bencDict = between (char 'd') (char 'e') $ fromList <$> many kvpair
- where kvpair = do k <- bencStr
+ where kvpair = do k <- bdictKey
v <- bencVal
- return (unpack k, v)
+ return (k, v)
+ bdictKey = do
+ ds <- many1 digit <* char ':'
+ s <- count (read ds) alphaNum
+ return s
+
bencVal :: ParsecBS.Parser BVal
bencVal = Bstr <$> bencStr <|>
where
kvlist :: [ByteString]
kvlist = [encPair kv | kv <- toList d]
- encPair (k, v) = concat [encode . Bstr . pack $ k, encode v]
+ encPair (k, v) = concat [encode (Bstr (pack k)), encode v]
let encoded = encode (Bint i)
decoded = decode encoded
in Right (Bint i) == decoded
- -- describe "Bencode property tests" $ do
- -- it "encode/decode" $ do
- -- property $ \bval ->
- -- let encoded = encode bval
- -- decoded = decode encoded
- -- in Right bval == decoded
+ it "encode/decode blist tests" $ do
+ property $ \bval ->
+ let encoded = encode (Blist (take 1 bval))
+ decoded = decode encoded
+ in Right (Blist (take 1 bval)) == decoded
+ -- it "encode/decode" $ do
+ -- property $ \bval ->
+ -- let encoded = encode bval
+ -- decoded = decode encoded
+ -- in Right bval == decoded