summaryrefslogtreecommitdiff
path: root/src/Data/Torrent/JSON.hs
blob: 845b288a0ce43b6fb372e7b1ca72d74e697bb159 (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
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Data.Torrent.JSON
       ( omitLensPrefix
       , omitRecordPrefix
       ) where

import Control.Applicative
import Data.Aeson.TH
import Data.Aeson.Types
import Data.ByteString as BS
import Data.ByteString.Base16 as Base16
import Data.Char
import Data.IP
import Data.List as L
import Data.Text.Encoding as T


-- | Ignore '_' prefix.
omitLensPrefix :: Options
omitLensPrefix = defaultOptions
  { fieldLabelModifier     = L.dropWhile (== '_')
  , constructorTagModifier = id
  , allNullaryToStringTag  = True
  , omitNothingFields      = True
  }

mapWhile :: (a -> Bool) -> (a -> a) -> [a] -> [a]
mapWhile p f = go
  where
    go []       = []
    go (x : xs)
      |    p x    = f x : go xs
      | otherwise = x : xs

omitRecordPrefix :: Options
omitRecordPrefix = omitLensPrefix
  { fieldLabelModifier = mapWhile isUpper toLower . L.dropWhile isLower
  }

instance ToJSON ByteString where
  toJSON = String . T.decodeUtf8 . Base16.encode

instance FromJSON ByteString where
  parseJSON v = do
    (ok, bad) <- (Base16.decode . T.encodeUtf8) <$> parseJSON v
    if BS.null bad
      then return ok
      else fail   "parseJSON: unable to decode ByteString"

instance ToJSON IP where
  toJSON = toJSON . show

instance FromJSON IP where
  parseJSON v = do
    str <- parseJSON v
    return $ read str