Converting things to and from binary
George Russell
ger@tzi.de
Wed, 21 May 2003 18:34:52 +0200
I wrote
>See the message I just
> posted the libraries list for a better example.
> http://haskell.org/pipermail/libraries/2003-May/001006.html
to which Hal Daume wrote (snipped)
> Why not use a state transformer on top of IO or something like that?
Er, how exactly does a state transformer allow my implementation of
put :: BinHandle -> a -> IO (BinPtr a)
to get at the extra state?
>Another one would be where you want to read some data from
>an untrusted client, limiting the number of bytes you can be bothered
>to read. This could be done using my framework by extending the monad
>with a count, it can't be done in Malcolm's framework, at least not
>without introducing an extra first step to do the IO.
>
>
> Hrm, this is interesting :). It seems like you should be able to use
> lazyGet to achieve this. Opening a BinIO doesn't actually cause it to be
> read until you actually do some of the reading. Using lazyGet should
> enable you to just read the amount you need to read under certain
> circumstances. I envision something like:
>
> newtype UntrustedString = UntrustedString String
>
> instance Binary UntrustedString where
[..]
That's not quite what I want, what I want is a way of reading a type
with an existing binary representation, throwing an exception if you
try to read too many characters. Of course it's possible with
Malcolm's framework to define a set of parallel types to the standard
Haskell ones (UntrustedInt, UntrustedString, and so on) and define new
instances of Binary for the lot, but this would be painful in general.
And you'd have to do it all over again should you want to put something
else inbetween the individual read/write operations (logging, online
compression, and so on) and the actual output.
However I use the counting-bytes example because I implemented it a few
weeks ago (writing server code, if you want to know), except that I
did it inelegantly, before I thought of this new framework.
As I said before, I have twice written inelegant converters to and from
binary, in the project I am now working on. It occurs to me that in both
cases I need some sort of extra state or information, meaning that in
neither case would Malcolm's framework have been of use without hackery.