[Haskell-cafe] Data.Binary, strict reading

Neil Mitchell ndmitchell at gmail.com
Thu Feb 26 04:17:21 EST 2009


Hi

> With binary 0.5,
>
>    src <- decodeFile "_make/_make"
>    return $! src

I'm pretty sure I was on the latest Cabal released version of binary,
and the above trick did not work. It _usually_ worked, but every so
often  I'd get a locking error.

> Shouldn't you use rnf[1]? Also, there seems to be binary-strict on
> Hackage, but I don't know if it is being maintained anymore.

Map.size is rnf on maps, I know exactly what its doing so in this case
I'm willing to cheat a little - but rnf would certainly be the more
principled way of doing it.

> I suggest you use withFile instead and decode from the Handle that gives
> you (via hGetContents) rather than decodeFile from the file name. That
> makes it much clearer. Of course you have to avoid doing lazy stuff, but
> that should be ok, Binary is strict in reading by default.

That was my first attempt, but the types didn't match up. I can
withFile using a System.IO handle, but Data.Binary doesn't seem to be
able to start going from a Handle. I guess I have to hop via the
ByteString bit myself with hGetContents. That's perfectly fine, and
much better than currently. However

> readDB = io $ (dbLocation >>= r) `catch` (λ_ →  return empty)
>       where r x = fmap (decode · BL.fromChunks · return) $ B.readFile x

This seems to be a very nice way of doing it, the strictness is
explicit in the ByteString.readFile. I've gone for this in my code.

Thanks

Neil


More information about the Haskell-Cafe mailing list