Reading/Writing Binary Data in Haskell
Glynn Clements
glynn.clements@virgin.net
Wed, 9 Jul 2003 04:31:11 +0100
Gordon James Miller wrote:
> 1 - Is there yet a standard, or at least commonly supported by hugs and
> ghc, method for dealing with binary data.
>
> 2 - If not, is there a "standard" library that is used to manipulate
> binary data. I've seen some references to some implementations but
> given that this is being done in my limited spare time (I'm not a full
> time student) I'd rather not spin my wheels on something that's going
> to be dead in a matter of months.
There isn't a standard mechanism for binary I/O.
However, a simple and fairly generic mechanism for doing this is:
1. Read in a list of "Char"s with the standard I/O functions.
2. Use "map (fromIntegral . ord) ..." to get a list of "Word8"s (octets).
3. Use with, poke, peek, castPtr etc to coerce a list of octets to the
desired type(s).
For output, do the reverse.
This way, you can read/write any instance of Storable in the host's
native format (i.e. "C" format), and the code should be portable.
The key here is step 3; if you want to sacrifice portability for
performance, use Posix.read (or the Win32 equivalent) to read directly
into memory (Ptr/Addr), or even write an import declaration for
mmap().
--
Glynn Clements <glynn.clements@virgin.net>