From 949bece818bc1bfd25c752e090890f9bd9cc078c Mon Sep 17 00:00:00 2001 From: "Scott R. Parish" Date: Mon, 18 Jan 2010 10:22:57 -0600 Subject: [PATCH] class for toBson/fromBson, instances for Maybe For example, you can now use fromBson of Maybe BsonValue (eg the result of a lookup) to convert to Maybe a. You can also give a Maybe a to toBson and for Nothing it will produce BsonNull and for Just a it will create the appropriate BsonValue for a. --- Database/MongoDB/BSON.hs | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/Database/MongoDB/BSON.hs b/Database/MongoDB/BSON.hs index c597f62..21b61d9 100644 --- a/Database/MongoDB/BSON.hs +++ b/Database/MongoDB/BSON.hs @@ -261,11 +261,17 @@ putOutterObj bytes = do putDataType :: DataType -> Put putDataType = putI8 . fromDataType -fromBson :: Convertible BsonValue a => BsonValue -> a -fromBson = convert +class BsonConv a b where + fromBson :: Convertible a b => a -> b + toBson :: Convertible b a => b -> a -toBson :: Convertible a BsonValue => a -> BsonValue -toBson = convert +instance BsonConv BsonValue a where + fromBson = convert + toBson = convert + +instance BsonConv (Maybe BsonValue) (Maybe a) where + fromBson = convert + toBson = convert unsupportedError :: (Typeable a, Convertible BsonValue a) => BsonValue -> ConvertResult a @@ -343,6 +349,11 @@ instance Convertible Int32 BsonValue where instance Convertible Int64 BsonValue where safeConvert i = return $ BsonInt64 i +instance (Convertible a BsonValue) => + Convertible (Maybe a) BsonValue where + safeConvert Nothing = return BsonNull + safeConvert (Just a) = safeConvert a + instance Convertible BsonValue Double where safeConvert (BsonDouble d) = return d safeConvert (BsonInt32 i) = safeConvert i @@ -426,3 +437,8 @@ instance Convertible BsonValue Int64 where safeConvert (BsonInt32 d) = safeConvert d safeConvert (BsonInt64 d) = return d safeConvert v = unsupportedError v + +instance (Convertible BsonValue a) => + Convertible (Maybe BsonValue) (Maybe a) where + safeConvert Nothing = return Nothing + safeConvert (Just a) = liftM Just $ safeConvert a