Commits

FlorianHartwig committed 5a2b574

Introduce FromBencode type class

  • Participants
  • Parent commits d0a6420

Comments (0)

Files changed (1)

File src/Data/AttoBencode/Types.hs

 import qualified Data.Map as M
 import Data.ByteString (ByteString)
 import qualified Data.ByteString.Char8 as B
+import Data.Traversable (traverse)
 
 -- | The Haskell data type for Bencode values
 data BValue = BString !ByteString
 class ToBencode a where
     toBencode :: a -> BValue
 
+-- | A type that can be converted from a BValue. The conversion can fail.
+class FromBencode a where
+    fromBencode :: BValue -> Maybe a
+
 instance ToBencode ByteString where
     toBencode = BString
 
 instance ToBencode BValue where
     toBencode = id
 -- TODO: make sure these are inlined
+
+
+instance FromBencode ByteString where
+    fromBencode (BString bs) = Just bs
+    fromBencode _            = Nothing
+
+instance FromBencode Integer where
+    fromBencode (BInt n) = Just n
+    fromBencode _        = Nothing
+
+instance (FromBencode a) => FromBencode (M.Map ByteString a) where
+    fromBencode (BDict d) = traverse fromBencode d
+    fromBencode _         = Nothing
+
+instance (FromBencode a) => FromBencode [a] where
+    fromBencode (BList l) = traverse fromBencode l
+    fromBencode _         = Nothing