Included a better API for converting to/from Eben
Getty Ritter
8 years ago
1 | 1 | {-# LANGUAGE OverloadedStrings #-} |
2 | 2 | {-# LANGUAGE ViewPatterns #-} |
3 | {-# LANGUAGE FlexibleInstances #-} | |
3 | 4 | |
4 | 5 | module Data.Eben where |
5 | 6 | |
58 | 59 | (str, rs'') = BS.splitAt len (BS.tail rs') |
59 | 60 | in Just (BS.toStrict str, rs'') |
60 | 61 | |
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 | ||
61 | 82 | asDict :: Value -> Maybe (Map B.ByteString Value) |
62 | 83 | asDict (Dict ds) = Just ds |
63 | 84 | asDict _ = Nothing |
86 | 107 | toNum (n * 10 + toDigit b) bs |
87 | 108 | toNum n _ = n |
88 | 109 | |
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 | ||
89 | 131 | encode :: Value -> ByteString |
90 | 132 | encode = BL.toLazyByteString . go |
91 | 133 | where go (List vs) = |