forked from astro/bitlove-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBenc.hs
48 lines (42 loc) · 1.32 KB
/
Benc.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
module Benc where
import Prelude
import Data.Monoid
import Data.List (sort)
import qualified Data.ByteString.Char8 as BC
import qualified Data.ByteString.Lazy.Char8 as LBC
import Blaze.ByteString.Builder
import Data.String
data BValue = BInt Integer
| BString LBC.ByteString
| BList [BValue]
| BDict [(BValue, BValue)]
deriving (Show, Eq, Ord)
instance IsString BValue where
fromString = BString . LBC.pack
-- FIXME: Builder inserts newlines between each chunk?
toBuilder :: BValue -> Builder
toBuilder (BString s) =
mconcat [ fromByteString $ BC.pack $ show $ LBC.length s
, fromByteString ":"
, fromLazyByteString s
]
toBuilder (BInt i) =
mconcat [ fromByteString "i"
, fromByteString $ BC.pack $ show i
, fromByteString "e"
]
toBuilder (BList xs) =
mconcat [ fromByteString "l"
, mconcat $ map toBuilder xs
, fromByteString "e"
]
toBuilder (BDict xs) =
let xs' = sort xs
in mconcat [ fromByteString "d"
, mconcat $
map (\(k, v) ->
toBuilder k `mappend`
toBuilder v
) xs'
, fromByteString "e"
]