[Haskell-cafe] binary IO

Bulat Ziganshin bulatz at HotPOP.com
Tue Dec 27 04:21:00 EST 2005


Hello Pupeno,

Tuesday, December 27, 2005, 7:10:24 AM, you wrote:

P> It seems I have found a hole in Haskell... :(

lazy language can't contain holes, they are just yet unevaluated thunks :)

P> I basically need a set of functions to read binary data out of a Handle (a
P> higher lever of hGetBuf and hPutBuf). What I am doing is implementing a DNS 
P> server, so, my typical need is:
P> First two bytes are an integer.
P> The next bit is a boolean.
P> So are the following three bits.
P> Then I have 4 bits which is also an integer.

it's my day :)

main = do h <- openBinaryFile "test" WriteMode
          bh <- openBitAligned h
          putWord16 bh   (101::Int)
          put_      bh   True
          putBits   bh 3 (2::Int)
          flushBits bh
          hClose h
          
          h <- openBinaryFile "test" ReadMode
          bh <- openBitAligned h
          a <- getWord16 bh  :: IO Int
          b <- get bh        :: IO Boolean
          c <- getBits bh 3  :: IO Int
          print (a,b,c)
          hClose h

http://freearc.narod.ru/Binary.tar.gz

but the better way is defining instance of Binary class:

data DNS = DNS Int Bool Int   deriving Show

instance Binary DNS where
  put_ bh (DNS a b c) = do putWord16 bh a
                           put_ bh b
                           putBits bh 3 c
  get bh = do a <- getWord16 bh
              b <- get bh
              c <- getBits bh 3
              return (DNS a b c)

main = do h <- openBinaryFile "test" WriteMode
          bh <- openBitAligned h
          put_ bh (DNS 37 True 3)
          flushBits bh
          hClose h
          
          h <- openBinaryFile "test" ReadMode
          bh <- openBitAligned h
          dns <- get bh :: IO DNS
          print dns
          hClose h

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

disclaimer: the library was written in last 3 weeks, and you will be
(if you want) its first user :)

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





More information about the Haskell-Cafe mailing list