Commits

FlorianHartwig committed fc86e27

Get rid of some boilerplate code and magic numbers

Comments (0)

Files changed (2)

src/Data/AttoBencode/Encode.hs

 
 import Data.AttoBencode.Types
 import Blaze.ByteString.Builder
+import Blaze.ByteString.Builder.Char.Utf8 (fromShow)
 import Data.Map (toAscList)
 import Data.Monoid
 import qualified Data.ByteString.Char8 as B
+import Data.Word (Word8)
 
 encode :: BValue -> B.ByteString
 encode = toByteString . fromBValue
 
+dWord, iWord, eWord, lWord, colon :: Word8
+dWord = 100
+eWord = 101
+lWord = 108
+iWord = 105
+colon = 58
+
 -- TODO: check out associativity of <>
--- TODO: get rid of magic numbers
 fromBValue :: BValue -> Builder
 fromBValue (BString s) = fromString s
-fromBValue (BList l)   = fromWord8 108 <> (mconcat . map fromBValue) l <> fromWord8 101
-fromBValue (BDict d)   = fromWord8 100 <> (mconcat . map fromPair) (toAscList d) <> fromWord8 101
-fromBValue (BInt n)    = fromWord8 105 <> toBuilder n <> fromWord8 101
+fromBValue (BList l)   = fromWord8 lWord <> (mconcat . map fromBValue) l <> fromWord8 eWord
+fromBValue (BDict d)   = fromWord8 dWord <> (mconcat . map fromPair) (toAscList d) <> fromWord8 eWord
+fromBValue (BInt n)    = fromWord8 iWord <> fromShow n <> fromWord8 eWord
 
 fromString :: B.ByteString -> Builder
-fromString s = toBuilder (B.length s) <> fromWord8 58 <> fromByteString s
+fromString s = fromShow (B.length s) <> fromWord8 colon <> fromByteString s
 {-# INLINE fromString #-}
 
 fromPair :: (B.ByteString, BValue) -> Builder
 fromPair (k, v) = fromString k <> fromBValue v
-
--- TODO: this is awful, find better way to do this
-toBuilder :: Show a => a -> Builder
-toBuilder = fromByteString . B.pack . show
-{-# INLINE toBuilder #-}
-{-# SPECIALISE toBuilder :: Integer -> Builder #-}
-{-# SPECIALISE toBuilder :: Int -> Builder #-}
--- TODO: see if specialising and inlining make a difference

src/Data/AttoBencode/Parser.hs

 {-# LANGUAGE BangPatterns #-}
 module Data.AttoBencode.Parser 
     ( decode
-    , getList
-    , getDict
-    , getInteger
-    , getString
     , bValue
     ) where
 
 import Data.Map
 import qualified Data.ByteString as B
 
--- TODO: replace using TH
-getString :: BValue -> B.ByteString
-getString (BString s) = s
-getString _           = error "Not a string"
-
-getInteger :: BValue -> Integer
-getInteger (BInt n) = n
-getInteger _        = error "Not an integer"
-
-getList :: BValue -> [BValue]
-getList (BList l) = l
-getList _         = error "Not a list"
-
-getDict :: BValue -> Dict
-getDict (BDict d) = d
-getDict _         = error "Not a dictionary"
-
 decode :: B.ByteString -> Maybe BValue
 decode = maybeResult . parse bValue