[Haskell] Using newArray with hGetArray
Andre Pang
ozone at algorithm.com.au
Mon May 23 12:03:04 EDT 2005
Hi all, I have the following snippet of code:
mutableMemoryArray <- newArray_ (0, bufferSize - 1)
bytesRead <- hGetArray handle mutableMemoryArray bufferSize
The problem is that hGetArray (like hGetBuf) may read less than the
amount that you specify (since you may hit EOF before filling up the
whole array). If this happens, the mutableMemoryArray array has a
bounds which is greater than it should be. This is quite bad if,
say, you hPutArray the array to another writable Handle.
e.g. if bufferSize is 4096, and the input file is 4100 bytes long,
the code will properly read 4096 bytes on the first pass, but only 4
bytes on the second pass; yet the bounds of the array will still be
4096 bytes in both cases, rather than 4096 and 4. You can't simply
swap the two expressions since you don't know how many bytes you've
read until you execute hGetArray, and you can't execute hGetArray
until you allocate the array, which requires that you know the array
bounds. Chicken-and-egg.
Am I missing something obvious here? I'd even be happy if there was
some way to adjust the bounds on a mutable array after it's been
created, or even if I could use hGetBuf and somehow efficiently
create an array from a (Ptr Word8). I know I could simply re-
allocate another array and garbage collect the first one if
bytesRead /= bufferSize, but that seems pretty inelegant.
Thanks!
--
% Andre Pang : trust.in.love.to.save <http://www.algorithm.com.au/>
More information about the Haskell
mailing list