[Haskell-cafe] binary IO

Bulat Ziganshin bulatz at HotPOP.com
Tue Dec 27 10:50:09 EST 2005


Hello Pupeno,

Tuesday, December 27, 2005, 6:03:50 PM, you wrote:

>> you must use `openBitAligned` to open bit-aligned stream over Handle,
>> and use `flushBits` at the end of writing. there is much more
>> features, ask me about what you need
P> Well, it seems I am seeing a bit of light here :)
P> I have a couple of questions:
P> - Is it possible to serialize from and to a Ptr ? Because TCP gives me a 
P> Handle, but UDP just gives me a Ptr with the packet and I'll turn the TCP 
P> into a Ptr as well.

reading:

h <- openMemory ptr size
bh <- openBitAligned h
a <- get bh
b <- get bh
....
-- you don't need to close/flush/free resources at the end

writing:

h <- createMemoryStream 64  -- replace 64 with initial buffer size you need
                            -- the buffer will be extended if more data
                            -- will be written
bh <- openBitAligned h
put_ bh a
put_ bh b
...
flushBits bh

but currently there is no way to get data from this buffer :)  just
see structure of SimpleMemoryStream (created by createMemoryStream)
and extract these data yourself - something like:

copyMemToHandle mem handle = do
  let (Mem buf' pos' end') = mem
  buf <- readPtr buf'
  pos <- readPtr pos'
  hPutBuf handle buf (pos-:buf)

P> - Is it possible to serialize from and to a Ptr ? Because TCP gives me a
P> Handle, but UDP just gives me a Ptr with the packet and I'll turn the TCP 
P> into a Ptr as well.

btw, you don't need to "convert" anything, my library works with
Handle and memory buffers in the same way. so just parse data directly
from the original source

P> - Is it possible to specify the endiannes ? I need to read everything as 
P> big-endian.

my library works in network format which is what you used in
ptrToWord16BE. if you need another format - you can either define and
use new low-level functions:

  getWord16LE h = do w1 <- vGetByte h
                     w2 <- vGetByte h
                     return $! ((w2 `shiftL` 8) .|. w1)

or define these functions and use them in defining instances of Binary
class:

instance Binary Word16 where
    put_ = putWord16LE
    get  = getWord16LE

instance Binary Word32 where
    put_ = putWord32LE
    get  = getWord32LE
....

and then just read Word16/Word32/... types. the second solution needs
to edit Binary.hs


-- 
Best regards,
 Bulat                            mailto:bulatz at HotPOP.com





More information about the Haskell-Cafe mailing list