on master help sign in
Make ensureBits pull just enough bytes from binary

Previously we let ensureBits take the internal state from binary (a bytestring chunk) but the master branch of binary does not allow this. Instead, read exactly as many bytes we need, each time we need something.

commit771f4b233f1d9c17b63e612f60d27320eb1dc1c7 authorLennart Kolmodin <kolmodin@gmail.com> dateWed 1 Jun 2011, 10:13 (15 years ago) parent0285c99
1 file changed+7−10
BitsGet.hs+7−10
BitsGet.hs+7−10
@@ -19,7 +19,7 @@ module BitsGet
1919
2020 ) where
2121
22−import Data.Binary.Get ( runGet, Get, needMore, getByteString, getS, putS )
22+import Data.Binary.Get ( runGet, Get, getByteString )
2323
2424import Data.ByteString as B
2525import Data.ByteString.Internal
@@ -254,15 +254,11 @@ runBitGetSimple bg = do
254254
255255runBitGet :: BitGet a -> Get (Either String a)
256256runBitGet bg = do
257− bs <- getS -- get the current chunk
258− putS B.empty
257+ let bs = B.empty -- initial state
259258 v <- runCont bg (S bs 0) (\str -> return (Left str)) (\s a -> return (Right (s, a)))
260259 case v of
261260 Left err -> return (Left err)
262− Right ((S bs' n), x) -> do
263− let bs'' | n > 0 = B.tail bs'
264− | otherwise = bs'
265− putS bs''
261+ Right ((S _bs' _n), x) -> do
266262 return (Right x)
267263
268264-- | Make sure there are at lest @n@ bits.
@@ -270,9 +266,10 @@ ensureBits :: Int -> BitGet ()
270266ensureBits n = C $ \s kf ks ->
271267 let loop (S bs o) | n <= (B.length bs * 8 - o) = ks (S bs o) ()
272268 | otherwise = do
273− needMore
274− bs' <- getS
275− putS B.empty
269+ let currentBits = B.length bs * 8 - o
270+ let byteCount = (n - currentBits + 7) `div` 8
271+ bs' <- getByteString byteCount
272+ -- should always be enough going once throguh the loop
276273 loop (S (bs`append`bs') o)
277274 in loop s
278275