@@ -82,6 +82,7 @@ module Data.Binary.Bits.Get
84import Data.Binary.Get as B ( runGet, Get, getByteString )
84import Data.Binary.Get as B ( runGet, Get, getByteString )
85+import Data.Binary.Get.Internal as B ( get, put, ensureN )
86import Data.ByteString as B
87import Data.ByteString as B
87import Data.ByteString.Unsafe
88import Data.ByteString.Unsafe
@@ -335,7 +336,7 @@ newtype BitGet a = B { runState :: S -> Get (S,a) }
336instance Monad BitGet where
337instance Monad BitGet where
337 return x = B $ \s -> return (s,x)
338 return x = B $ \s -> return (s,x)
338− fail str = B $ \_s -> fail str
339+ fail str = B $ \(S inp n) -> putBackState inp n >> fail str
339 (B f) >>= g = B $ \s -> do (s',a) <- f s
340 (B f) >>= g = B $ \s -> do (s',a) <- f s
340 runState (g a) s'
341 runState (g a) s'
@@ -350,9 +351,22 @@ instance Applicative BitGet where
350-- been partially consumed it will be discarded once 'runBitGet' is finished.
351-- been partially consumed it will be discarded once 'runBitGet' is finished.
351runBitGet :: BitGet a -> Get a
352runBitGet :: BitGet a -> Get a
352runBitGet bg = do
353runBitGet bg = do
353− (_,a) <- runState bg (S B.empty 0)
355+ ((S str' n),a) <- runState bg s
365+putBackState :: B.ByteString -> Int -> Get ()
366+putBackState bs n = do
368+ put (B.drop (if n==0 then 0 else 1) bs `B.append` remaining)
356getState :: BitGet S
370getState :: BitGet S
357getState = B $ \s -> return (s,s)
371getState = B $ \s -> return (s,s)
@@ -370,7 +384,9 @@ ensureBits n = do
370 then return ()
384 then return ()
371 else do let currentBits = B.length bs * 8 - o
385 else do let currentBits = B.length bs * 8 - o
372 let byteCount = (n - currentBits + 7) `div` 8
386 let byteCount = (n - currentBits + 7) `div` 8
373− B $ \_ -> do bs' <- B.getByteString byteCount
387+ B $ \_ -> do B.ensureN byteCount
374 return (S (bs`append`bs') o, ())
390 return (S (bs`append`bs') o, ())
376-- | Get 1 bit as a 'Bool'.
392-- | Get 1 bit as a 'Bool'.