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).
Asked
Active
Viewed 321 times
3
-
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`, `avro`, `attoparsec`, etc). – Thomas M. DuBuisson Aug 01 '16 at 17:08
-
1Since [AVP header layout depends on the flags](https://tools.ietf.org/html/rfc6733#page-41) you can't really do it with `StructLayout` either. – Cirdec Aug 01 '16 at 19:40
-
You are right Cirdec, but I want to know the solution anyway for other uses. – Kamyar Aug 02 '16 at 08:07
-
Let me clarify my requirement more: In Python we can create a class with initialization constructor, and then use Struct package and * operator to map class fields to bytes format: `class MyTest: def __init__(x:int, y:int): self.x=x self.y=y m=MyTest(*struct.unpack('il'), b'\x00\x01\x00\x02\x00\x00\x00\x03')` – Kamyar Aug 02 '16 at 09:16
1 Answers
2
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.

Thomas M. DuBuisson
- 64,245
- 7
- 109
- 166
-
I do not mean under the hood layout necessarily, I mean something simulating it, like in Python: struct package helps very much to convert bytestring (bytes in Python 3) to a standard Python class/tuple. – Kamyar Aug 02 '16 at 08:05
-
1@Kamyar Binary instances provide exactly that though, so I still don't understand the problem. – Thomas M. DuBuisson Aug 02 '16 at 16:06