Search code examples
haskellbinarynetwork-programmingpacketbytestring

How can I map a binary network packet structure to Haskell standard data types (records)?


I want to implement a binary protocol (RFC3588, Diameter) with pure Haskell. I need to know is there any better way (Than e.g. Data.Binary...) to read/write data from/to ByteStrings. I like mapping a Haskell record to ByteString, as like what is usual in C# using StructLayout attribute (decorator).


Solution

  • Haskell does not give you any guarantees about memory layout so you can not simply cast a set of bytes as a struct - you must parse it using binary or something rather like it (cereal, attoparsec, etc).

    EDIT: For an example use of binary, consider:

    {-# LANGUAGE DeriveGeneric #-}
    
    import Data.Binary
    import GHC.Generics (Generic)
    
    data Foo = Foo Int | Bar String deriving (Eq, Ord, Show, Read, Generic)
    
    instance Binary Foo
    

    Now you can encode and decode the Foo type to and from bytes.