gdritter repos eben / 8d8bac9
Included a better API for converting to/from Eben Getty Ritter 8 years ago
1 changed file(s) with 42 addition(s) and 0 deletion(s). Collapse all Expand all
11 {-# LANGUAGE OverloadedStrings #-}
22 {-# LANGUAGE ViewPatterns #-}
3 {-# LANGUAGE FlexibleInstances #-}
34
45 module Data.Eben where
56
5859 (str, rs'') = BS.splitAt len (BS.tail rs')
5960 in Just (BS.toStrict str, rs'')
6061
62 class FromEben t where
63 fromEben :: Value -> Maybe t
64
65 instance FromEben Float where
66 fromEben (Float f) = Just f
67 fromEben (Integer i) = Just (fromIntegral i)
68 fromEben _ = Nothing
69
70 instance FromEben Int where
71 fromEben (Integer i) = Just (fromIntegral i)
72 fromEben _ = Nothing
73
74 instance FromEben a => FromEben [a] where
75 fromEben (List ls) = mapM fromEben ls
76 fromEben _ = Nothing
77
78 instance (FromEben a, FromEben b) => FromEben (a, b) where
79 fromEben (List [x,y]) = (,) <$> fromEben x <*> fromEben y
80 fromEben _ = Nothing
81
6182 asDict :: Value -> Maybe (Map B.ByteString Value)
6283 asDict (Dict ds) = Just ds
6384 asDict _ = Nothing
86107 toNum (n * 10 + toDigit b) bs
87108 toNum n _ = n
88109
110 class ToEben t where
111 toEben :: t -> Value
112
113 instance ToEben a => ToEben [a] where
114 toEben = List . map toEben
115
116 instance ToEben Float where
117 toEben = Float
118
119 instance ToEben Int where
120 toEben = Integer . fromIntegral
121
122 instance ToEben Integer where
123 toEben = Integer . fromIntegral
124
125 instance (ToEben l, ToEben r) => ToEben (l, r) where
126 toEben (x, y) = List [ toEben x, toEben y ]
127
128 dict :: [(B.ByteString, Value)] -> Value
129 dict = Dict . M.fromList
130
89131 encode :: Value -> ByteString
90132 encode = BL.toLazyByteString . go
91133 where go (List vs) =