summaryrefslogtreecommitdiff
path: root/src/Data/BEncode/Types.hs
blob: 15f570f0c90315645e1d3898d87858dd06bf778a (plain)
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
-- |
--   Copyright   :  (c) Sam Truzjan 2013
--   License     :  BSD3
--   Maintainer  :  pxqr.sta@gmail.com
--   Stability   :  stable
--   Portability :  portable
--
--   Types for working with bencode data.
--
module Data.BEncode.Types
       ( -- * Types
         BInteger
       , BString
       , BList
       , BDict
       , BValue (..)

         -- * Predicates
       , isInteger
       , isString
       , isList
       , isDict
       ) where

import Control.DeepSeq
import Data.ByteString

import Data.BEncode.BDict

-- | A bencode "integer".
type BInteger = Integer

-- | A raw bencode string.
type BString  = ByteString

-- | A plain bencode list.
type BList    = [BValue]

-- | A bencode dictionary.
type BDict    = BDictMap BValue

-- | 'BValue' is straightforward ADT for b-encoded values. Please
-- note that since dictionaries are sorted, in most cases we can
-- compare BEncoded values without serialization and vice versa.
-- Lists is not required to be sorted through.
--
data BValue
  = BInteger !BInteger -- ^ bencode integers;
  | BString  !BString  -- ^ bencode strings;
  | BList     BList    -- ^ list of bencode values;
  | BDict     BDict    -- ^ bencode key-value dictionary.
    deriving (Show, Read, Eq, Ord)

instance NFData BValue where
    rnf (BInteger i) = rnf i
    rnf (BString  s) = rnf s
    rnf (BList    l) = rnf l
    rnf (BDict    d) = rnf d

{--------------------------------------------------------------------
  Predicates
--------------------------------------------------------------------}

-- | Test if bencoded value is an integer.
isInteger :: BValue -> Bool
isInteger (BInteger _) = True
isInteger _            = False
{-# INLINE isInteger #-}

-- | Test if bencoded value is a string, both raw and utf8 encoded.
isString :: BValue -> Bool
isString (BString _) = True
isString _           = False
{-# INLINE isString #-}

-- | Test if bencoded value is a list.
isList :: BValue -> Bool
isList (BList _) = True
isList _         = False
{-# INLINE isList #-}

-- | Test if bencoded value is a dictionary.
isDict :: BValue -> Bool
isDict (BList _) = True
isDict _         = False
{-# INLINE isDict #-}