Skip to content

Add From/ToFieldValue classes #78

@nikomi

Description

@nikomi

Thanx again for your AMQP library!

Here is something I added to my client which you might find useful:

type FieldEntry = (Text, FieldValue)

toFieldEntry ∷ ToFieldValue a ⇒ T.Text → a → FieldEntry
toFieldEntry k v = (k, toFieldValue v)

This relies on classes From/ToFieldValue:

class FromFieldValue a where
    fromFieldValue ∷ FieldValue → Maybe a

instance FromFieldValue () where
    fromFieldValue FVVoid = Just ()
    fromFieldValue _      = Nothing

instance FromFieldValue Bool where
    fromFieldValue (FVBool b) = Just b
    fromFieldValue _          = Nothing

instance FromFieldValue Int where
    fromFieldValue (FVInt8  i) = Just (fromIntegral i)
    fromFieldValue (FVInt16 i) = Just (fromIntegral i)
    fromFieldValue (FVInt32 i) = Just (fromIntegral i)
    fromFieldValue (FVInt64 i) = Just (fromIntegral i)
    fromFieldValue _      = Nothing

instance FromFieldValue ByteString where
    fromFieldValue (FVByteArray b) = Just b
    fromFieldValue _               = Nothing

instance FromFieldValue T.Text where
    fromFieldValue (FVString t) = Just t
    fromFieldValue _            = Nothing

instance FromFieldValue Float where
    fromFieldValue (FVFloat f)  = Just f
    fromFieldValue (FVDouble f) = Just (double2Float f)
    fromFieldValue _            = Nothing

instance FromFieldValue Double where
    fromFieldValue (FVDouble f) = Just f
    fromFieldValue (FVFloat f)  = Just (float2Double f)
    fromFieldValue _            = Nothing

and

class ToFieldValue a where
    toFieldValue ∷ a → FieldValue

instance ToFieldValue () where
    toFieldValue = const FVVoid

instance ToFieldValue Bool where
    toFieldValue = FVBool

instance ToFieldValue Int where
    toFieldValue = FVInt64 ∘ fromIntegral

instance ToFieldValue ByteString where
    toFieldValue = FVByteArray

instance ToFieldValue T.Text where
    toFieldValue = FVString

instance ToFieldValue Float where
    toFieldValue = FVFloat

instance ToFieldValue Double where
    toFieldValue = FVDouble

The integer handling could definitely be improved but this is all I needed for the moment.

Please feel free to add this to your AMQP library if you think it is useful.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions