blob: 6a0aa510399d18e07d9c3e035faa72131bee01cf (
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
|
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.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 = 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"
|