@@ -4,7 +4,6 @@
5-- Module : Data.Binary.Bits.Get
5-- Module : Data.Binary.Bits.Get
6-- Copyright : (c) Lennart Kolmodin 2010-2011
6-- Copyright : (c) Lennart Kolmodin 2010-2011
7−-- (c) Sylvain Henry 2015
8-- License : BSD3-style (see LICENSE)
7-- License : BSD3-style (see LICENSE)
10-- Maintainer : kolmodin@gmail.com
9-- Maintainer : kolmodin@gmail.com
@@ -56,11 +55,14 @@ module Data.Binary.Bits.Get
56 -- $bitget
55 -- $bitget
59 , runBitGet
59 , runBitGet
61 -- ** Get bytes
64 -- ** Get bytes
64 , getWord8
66 , getWord8
65 , getWord16
67 , getWord16
66 , getWord32
68 , getWord32
@@ -97,9 +99,6 @@ module Data.Binary.Bits.Get
98import Data.Binary.Get as B ( Get, getLazyByteString, isEmpty )
100import Data.Binary.Get as B ( Get, getLazyByteString, isEmpty )
99import Data.Binary.Get.Internal as B ( get, put, ensureN )
101import Data.Binary.Get.Internal as B ( get, put, ensureN )
100−import Data.Binary.Bits.BitOrder
101−import Data.Binary.Bits.Internal
102−import Data.Binary.Bits.Alignment
104import Data.ByteString as B
103import Data.ByteString as B
105import qualified Data.ByteString.Lazy as L
104import qualified Data.ByteString.Lazy as L
@@ -115,8 +114,12 @@ import Control.Applicative
115import Control.Monad (when,foldM_)
114import Control.Monad (when,foldM_)
117import Prelude as P
116import Prelude as P
118+#if defined(__GLASGOW_HASKELL__) && !defined(__HADDOCK__)
118import GHC.Word
120import GHC.Word
119−import GHC.Base (uncheckedShiftLWord8#, wordToWord8#, Int (..), andWord8#, Word8#, (-#), Int#, xorI#, eqWord8#, TYPE)
121+#endif
121-- $bitget
124-- $bitget
122-- Parse bits using a monad.
125-- Parse bits using a monad.
@@ -169,6 +172,16 @@ data S = S {-# UNPACK #-} !ByteString -- Input
169 !BitOrder -- Bit order
172 !BitOrder -- Bit order
170 deriving (Show)
173 deriving (Show)
175+-- | Compute bit offset (equivalent to x `mod` 8 but faster)
176+bit_offset :: Int -> Int
177+bit_offset n = make_mask 3 .&. n
178+{-# INLINE bit_offset #-}
180+-- | Compute byte offset (equivalent to x `div` 8 but faster)
181+byte_offset :: Int -> Int
182+byte_offset n = n `shiftR` 3
183+{-# INLINE byte_offset #-}
172-- | Increment the current bit offset
185-- | Increment the current bit offset
173incS :: Int -> S -> S
186incS :: Int -> S -> S
174incS o (S bs n bo) = S (unsafeDrop d bs) n' bo
187incS o (S bs n bo) = S (unsafeDrop d bs) n' bo
@@ -177,30 +190,58 @@ incS o (S bs n bo) = S (unsafeDrop d bs) n' bo
177 !d = byte_offset o'
190 !d = byte_offset o'
178 !n' = bit_offset o'
191 !n' = bit_offset o'
193+-- | Select the bit ordering
194+selectBitOrderS :: BitOrder -> S -> S
195+selectBitOrderS bo (S bs o _) = S bs o bo
197+-- | make_mask 3 = 00000111
198+make_mask :: (Bits a, Num a) => Int -> a
199+make_mask n = (1 `shiftL` fromIntegral n) - 1
200+{-# SPECIALIZE make_mask :: Int -> Int #-}
201+{-# SPECIALIZE make_mask :: Int -> Word #-}
202+{-# SPECIALIZE make_mask :: Int -> Word8 #-}
203+{-# SPECIALIZE make_mask :: Int -> Word16 #-}
204+{-# SPECIALIZE make_mask :: Int -> Word32 #-}
205+{-# SPECIALIZE make_mask :: Int -> Word64 #-}
207+-- | Keep only the n least-significant bits of the given value
208+mask :: (Bits a, Num a) => Int -> a -> a
209+mask n v = v .&. make_mask n
214+-- E.g. two words of 5 bits: ABCDE, VWXYZ
215+-- - BB: ABCDEVWX YZxxxxxx
216+-- - LB: XYZABCDE xxxxxxVW
217+-- - BL: EDCBAZYX WVxxxxxx
218+-- - LL: XWVEDCBA xxxxxxZY
219+data BitOrder = BB | LB | BL | LL deriving (Show)
221+-- | Reverse the @n@ least important bits of the given value
222+reverseBits :: (Num a, FastBits a, Bits a) => Int -> a -> a
223+reverseBits n value = rec value n 0
226+ -- v is orginal value shifted
227+ -- i is the remaining number of bits
228+ -- r is current value
230+ rec 0 i r = r `fastShiftL` i
231+ rec v i r = rec (v `fastShiftR` 1) (i-1) ((r `fastShiftL` 1) .|. (v .&. 0x1))
180-- | Read a single bit
233-- | Read a single bit
181readBool :: S -> Bool
234readBool :: S -> Bool
182readBool (S bs o bo) = case bo of
235readBool (S bs o bo) = case bo of
183 BB -> testBit (unsafeHead bs) (7-o)
236 BB -> testBit (unsafeHead bs) (7-o)
184 BL -> testBit (unsafeHead bs) (7-o)
237 BL -> testBit (unsafeHead bs) (7-o)
185− LL -> testBit (unsafeHead bs) o
186 LB -> testBit (unsafeHead bs) o
238 LB -> testBit (unsafeHead bs) o
188−-- | Read a single bit
189−readBool# :: S -> Int
190−readBool# (S bs (I# o) bo) = case bo of
191− BB -> testBit# (7# -# o)
192− BL -> testBit# (7# -# o)
196− !(W8# w) = unsafeHead bs
239+ LL -> testBit (unsafeHead bs) o
197− testBit# n = I# (((w `andWord8#` (wordToWord8# 1## `uncheckedShiftLWord8#` n)) `eqWord8#` wordToWord8# 0##) `xorI#` 1#)
200-- | Extract a range of bits from (ws :: ByteString)
241-- | Extract a range of bits from (ws :: ByteString)
202-- Constraint: 8 * (length ws -1 ) < o+n <= 8 * length ws
243-- Constraint: 8 * (length ws -1 ) < o+n <= 8 * length ws
203−extract :: (Num a, FastBits a) => BitOrder -> ByteString -> Int -> Int -> a
244+extract :: (Num a, Bits a, FastBits a) => BitOrder -> ByteString -> Int -> Int -> a
204extract bo bs o n
245extract bo bs o n
205 | n == 0 = 0
246 | n == 0 = 0
206 | B.length bs == 0 = error "Empty ByteString"
247 | B.length bs == 0 = error "Empty ByteString"
@@ -218,21 +259,21 @@ extract bo bs o n
219 -- shift offset depending on the byte position (0..B.length-1)
260 -- shift offset depending on the byte position (0..B.length-1)
220 off i = case bo of
261 off i = case bo of
222 LB -> 8*i - o
262 LB -> 8*i - o
223 BB -> (B.length bs -1 - i) * 8 - r
264 BB -> (B.length bs -1 - i) * 8 - r
224 BL -> (B.length bs -1 - i) * 8 - r
265 BL -> (B.length bs -1 - i) * 8 - r
226 -- reverse bits if necessary
267 -- reverse bits if necessary
227 rev = case bo of
268 rev = case bo of
228− LB -> reverseBits n
269+ LL -> reverseBits n
229 BL -> reverseBits n
270 BL -> reverseBits n
231− LL -> id
272+ LB -> id
234-- | Generic readWord
275-- | Generic readWord
235−readWord :: (Num a, FastBits a) => Int -> S -> a
276+readWord :: (Num a, Bits a, FastBits a) => Int -> S -> a
236readWord n (S bs o bo)
277readWord n (S bs o bo)
237 | n == 0 = 0
278 | n == 0 = 0
238 | otherwise = extract bo (unsafeTake nbytes bs) o n
279 | otherwise = extract bo (unsafeTake nbytes bs) o n
@@ -240,7 +281,7 @@ readWord n (S bs o bo)
241-- | Check that the number of bits to read is not greater than the first parameter
282-- | Check that the number of bits to read is not greater than the first parameter
242{-# INLINE readWordChecked #-}
283{-# INLINE readWordChecked #-}
243−readWordChecked :: (Num a, FastBits a) => Int -> Int -> S -> a
284+readWordChecked :: (Num a, Bits a, FastBits a) => Int -> Int -> S -> a
244readWordChecked m n s
285readWordChecked m n s
245 | n > m = error $ "Tried to read more than " ++ show m ++ " bits (" ++ show n ++")"
286 | n > m = error $ "Tried to read more than " ++ show m ++ " bits (" ++ show n ++")"
246 | otherwise = readWord n s
287 | otherwise = readWord n s
@@ -249,23 +290,22 @@ readWordChecked m n s
250-- Examples:
291-- Examples:
251-- BB: xxxABCDE FGHIJKLM NOPxxxxx -> ABCDEFGH IJKLMNOP
292-- BB: xxxABCDE FGHIJKLM NOPxxxxx -> ABCDEFGH IJKLMNOP
252−-- LL: LMNOPxxx DEFGHIJK xxxxxABC -> ABCDEFGH IJKLMNOP
293+-- LB: LMNOPxxx DEFGHIJK xxxxxABC -> ABCDEFGH IJKLMNOP
253-- BL: xxxPONML KJIHGFED CBAxxxxx -> ABCDEFGH IJKLMNOP
294-- BL: xxxPONML KJIHGFED CBAxxxxx -> ABCDEFGH IJKLMNOP
254−-- LB: EDCBAxxx MLKJIHGF xxxxxPON -> ABCDEFGH IJKLMNOP
295+-- LL: EDCBAxxx MLKJIHGF xxxxxPON -> ABCDEFGH IJKLMNOP
255readByteString :: Int -> S -> ByteString
296readByteString :: Int -> S -> ByteString
256readByteString n (S bs o bo) =
297readByteString n (S bs o bo) =
258− bs' = unsafeTake (n+1) bs
299+ bs' = unsafeTake (n+1) bs
259− bs'' = unsafeTake n bs
260− rev = B.map (reverseBits 8)
300+ rev = B.map (reverseBits 8)
261 in case (o,bo) of
301 in case (o,bo) of
262− (0,BB) -> bs''
302+ (0,BB) -> unsafeTake n bs
263− (0,LL) -> B.reverse bs''
303+ (0,LB) -> B.reverse (unsafeTake n bs)
264− (0,LB) -> rev bs''
304+ (0,BL) -> rev (unsafeTake n bs)
265− (0,BL) -> rev . B.reverse $ bs''
305+ (0,LL) -> rev (B.reverse (unsafeTake n bs))
266− (_,LL) -> readByteString n (S (B.reverse bs') (8-o) BB)
306+ (_,BL) -> rev (readByteString n (S (B.reverse bs') o LB))
267− (_,BL) -> rev . B.reverse $ readByteString n (S bs' o BB)
307+ (_,LL) -> rev (readByteString n (S (B.reverse bs') o BB))
268− (_,LB) -> rev . B.reverse $ readByteString n (S bs' o LL)
308+ (_,LB) -> readByteString n (S (B.reverse bs') o BB)
269 (_,BB) -> unsafePerformIO $ do
309 (_,BB) -> unsafePerformIO $ do
270 let len = n+1
310 let len = n+1
271 ptr <- mallocBytes len
311 ptr <- mallocBytes len
@@ -287,6 +327,7 @@ newtype BitGet a = B { runState :: S -> Get (S,a) }
288instance Monad BitGet where
328instance Monad BitGet where
289 return x = B $ \s -> return (s,x)
329 return x = B $ \s -> return (s,x)
330+ fail str = B $ \s -> putBackState s >> fail str
290 (B f) >>= g = B $ \s -> do (s',a) <- f s
331 (B f) >>= g = B $ \s -> do (s',a) <- f s
291 runState (g a) s'
332 runState (g a) s'
@@ -297,29 +338,6 @@ instance Applicative BitGet where
297 pure x = return x
338 pure x = return x
298 fm <*> m = fm >>= \f -> m >>= \v -> return (f v)
339 fm <*> m = fm >>= \f -> m >>= \v -> return (f v)
300−instance BitOrderable BitGet where
302− (S bs o _) <- getState
303− putState (S bs o bo)
306− (S _ _ bo) <- getState
309−instance Alignable BitGet where
310− -- | Skip the given number of bits
315− -- | Skip bits if necessary to align to the next byte
317− (S _ o _) <- getState
323-- | Run a 'BitGet' within the Binary packages 'Get' monad. If a byte has
341-- | Run a 'BitGet' within the Binary packages 'Get' monad. If a byte has
324-- been partially consumed it will be discarded once 'runBitGet' is finished.
342-- been partially consumed it will be discarded once 'runBitGet' is finished.
325runBitGet :: BitGet a -> Get a
343runBitGet :: BitGet a -> Get a
@@ -354,6 +372,13 @@ withState f = do
354 s <- getState
372 s <- getState
355 putState $! f s
373 putState $! f s
375+-- | Get the bit ordering
376+getBitOrder :: BitGet BitOrder
378+ (S _ _ bo) <- getState
357-- | Make sure there are at least @n@ bits.
382-- | Make sure there are at least @n@ bits.
358ensureBits :: Int -> BitGet ()
383ensureBits :: Int -> BitGet ()
359ensureBits n = do
384ensureBits n = do
@@ -367,6 +392,33 @@ ensureBits n = do
367 put B.empty
392 put B.empty
368 return (S (bs`append`bs') o bo, ())
393 return (S (bs`append`bs') o bo, ())
395+-- | Skip the given number of bits
396+skipBits :: Int -> BitGet ()
401+-- | Skip bits if necessary to align to the next byte
402+alignByte :: BitGet ()
404+ (S _ o _) <- getState
408+-- | Select the bit ordering
409+selectBitOrder :: BitOrder -> BitGet ()
410+selectBitOrder = withState . selectBitOrderS
412+withBitOrder :: BitOrder -> BitGet a -> BitGet a
413+withBitOrder bo f = do
370-- | Test whether all input has been consumed, i.e. there are no remaining
422-- | Test whether all input has been consumed, i.e. there are no remaining
371-- undecoded bytes.
423-- undecoded bytes.
372isEmpty :: BitGet Bool
424isEmpty :: BitGet Bool
@@ -378,10 +430,6 @@ isEmpty = B $ \ (S bs o bo) -> if B.null bs
378getBool :: BitGet Bool
430getBool :: BitGet Bool
379getBool = block bool
431getBool = block bool
381−-- | Get 1 bit as a 'Bool'.
382−getBool# :: BitGet Int
383−getBool# = block bool#
385-- | Get @n@ bits as a 'Word8'. @n@ must be within @[0..8]@.
433-- | Get @n@ bits as a 'Word8'. @n@ must be within @[0..8]@.
386getWord8 :: Int -> BitGet Word8
434getWord8 :: Int -> BitGet Word8
387getWord8 n = block (word8 n)
435getWord8 n = block (word8 n)
@@ -457,10 +505,6 @@ block (Block i p) = do
457bool :: Block Bool
505bool :: Block Bool
458bool = Block 1 readBool
506bool = Block 1 readBool
460−-- | Read a 1 bit 'Bool'.
462−bool# = Block 1 readBool#
464-- | Read @n@ bits as a 'Word8'. @n@ must be within @[0..8]@.
508-- | Read @n@ bits as a 'Word8'. @n@ must be within @[0..8]@.
465word8 :: Int -> Block Word8
509word8 :: Int -> Block Word8
466word8 n = Block n (readWordChecked 8 n)
510word8 n = Block n (readWordChecked 8 n)
@@ -494,3 +538,84 @@ byteString :: Int -> Block ByteString
494byteString n | n > 0 = Block (n*8) (readByteString n)
538byteString n | n > 0 = Block (n*8) (readByteString n)
495 | otherwise = Block 0 (\_ -> B.empty)
539 | otherwise = Block 0 (\_ -> B.empty)
542+---------------------------------------------------------------------
543+-- Unchecked shifts, from the "binary" package
545+-- | Class for types supporting fast bit shifting
546+class FastBits a where
547+ fastShiftR :: a -> Int -> a
548+ fastShiftL :: a -> Int -> a
550+ {-# INLINE fastShift #-}
551+ fastShift :: a -> Int -> a
553+ | n > 0 = fastShiftL x n
554+ | n < 0 = fastShiftR x (negate n)
557+instance FastBits Word8 where
558+ fastShiftR = shiftr_w8
559+ fastShiftL = shiftl_w8
561+instance FastBits Word16 where
562+ fastShiftR = shiftr_w16
563+ fastShiftL = shiftl_w16
565+instance FastBits Word32 where
566+ fastShiftR = shiftr_w32
567+ fastShiftL = shiftl_w32
569+instance FastBits Word64 where
570+ fastShiftR = shiftr_w64
571+ fastShiftL = shiftl_w64
574+shiftl_w8 :: Word8 -> Int -> Word8
575+shiftl_w16 :: Word16 -> Int -> Word16
576+shiftl_w32 :: Word32 -> Int -> Word32
577+shiftl_w64 :: Word64 -> Int -> Word64
579+shiftr_w8 :: Word8 -> Int -> Word8
580+shiftr_w16 :: Word16 -> Int -> Word16
581+shiftr_w32 :: Word32 -> Int -> Word32
582+shiftr_w64 :: Word64 -> Int -> Word64
584+#if defined(__GLASGOW_HASKELL__) && !defined(__HADDOCK__)
585+shiftl_w8 (W8# w) (I# i) = W8# (w `uncheckedShiftL#` i)
586+shiftl_w16 (W16# w) (I# i) = W16# (w `uncheckedShiftL#` i)
587+shiftl_w32 (W32# w) (I# i) = W32# (w `uncheckedShiftL#` i)
589+shiftr_w8 (W8# w) (I# i) = W8# (w `uncheckedShiftRL#` i)
590+shiftr_w16 (W16# w) (I# i) = W16# (w `uncheckedShiftRL#` i)
591+shiftr_w32 (W32# w) (I# i) = W32# (w `uncheckedShiftRL#` i)
594+#if WORD_SIZE_IN_BITS < 64
595+shiftl_w64 (W64# w) (I# i) = W64# (w `uncheckedShiftL64#` i)
596+shiftr_w64 (W64# w) (I# i) = W64# (w `uncheckedShiftRL64#` i)
598+#if __GLASGOW_HASKELL__ <= 606
599+-- Exported by GHC.Word in GHC 6.8 and higher
600+foreign import ccall unsafe "stg_uncheckedShiftL64"
601+ uncheckedShiftL64# :: Word64# -> Int# -> Word64#
602+foreign import ccall unsafe "stg_uncheckedShiftRL64"
603+ uncheckedShiftRL64# :: Word64# -> Int# -> Word64#
607+shiftl_w64 (W64# w) (I# i) = W64# (w `uncheckedShiftL#` i)
608+shiftr_w64 (W64# w) (I# i) = W64# (w `uncheckedShiftRL#` i)