@@ -4,7 +4,6 @@
44-- |
55-- Module : Data.Binary.Bits.Get
66-- Copyright : (c) Lennart Kolmodin 2010-2011
7−-- (c) Sylvain Henry 2015
87-- License : BSD3-style (see LICENSE)
98--
109-- Maintainer : kolmodin@gmail.com
@@ -56,11 +55,13 @@ module Data.Binary.Bits.Get
5655 -- $bitget
5756
5857 BitGet
58+ , BitOrder(..)
5959 , runBitGet
60+ , selectBitOrder
61+ , withBitOrder
6062
6163 -- ** Get bytes
6264 , getBool
63− , getBool#
6465 , getWord8
6566 , getWord16
6667 , getWord32
@@ -97,9 +98,6 @@ module Data.Binary.Bits.Get
9798
9899import Data.Binary.Get as B ( Get, getLazyByteString, isEmpty )
99100import 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
103101
104102import Data.ByteString as B
105103import qualified Data.ByteString.Lazy as L
@@ -115,8 +113,12 @@ import Control.Applicative
115113import Control.Monad (when,foldM_)
116114
117115import Prelude as P
116+
117+#if defined(__GLASGOW_HASKELL__) && !defined(__HADDOCK__)
118+import GHC.Base
118119import GHC.Word
119−import GHC.Base (uncheckedShiftLWord8#, wordToWord8#, Int (..), andWord8#, Word8#, (-#), Int#, xorI#, eqWord8#, TYPE)
120+#endif
121+
120122
121123-- $bitget
122124-- Parse bits using a monad.
@@ -169,6 +171,16 @@ data S = S {-# UNPACK #-} !ByteString -- Input
169171 !BitOrder -- Bit order
170172 deriving (Show)
171173
174+-- | Compute bit offset (equivalent to x `mod` 8 but faster)
175+bit_offset :: Int -> Int
176+bit_offset n = make_mask 3 .&. n
177+{-# INLINE bit_offset #-}
178+
179+-- | Compute byte offset (equivalent to x `div` 8 but faster)
180+byte_offset :: Int -> Int
181+byte_offset n = n `shiftR` 3
182+{-# INLINE byte_offset #-}
183+
172184-- | Increment the current bit offset
173185incS :: Int -> S -> S
174186incS o (S bs n bo) = S (unsafeDrop d bs) n' bo
@@ -177,30 +189,58 @@ incS o (S bs n bo) = S (unsafeDrop d bs) n' bo
177189 !d = byte_offset o'
178190 !n' = bit_offset o'
179191
192+-- | Select the bit ordering
193+selectBitOrderS :: BitOrder -> S -> S
194+selectBitOrderS bo (S bs o _) = S bs o bo
195+
196+-- | make_mask 3 = 00000111
197+make_mask :: (Bits a, Num a) => Int -> a
198+make_mask n = (1 `shiftL` fromIntegral n) - 1
199+{-# SPECIALIZE make_mask :: Int -> Int #-}
200+{-# SPECIALIZE make_mask :: Int -> Word #-}
201+{-# SPECIALIZE make_mask :: Int -> Word8 #-}
202+{-# SPECIALIZE make_mask :: Int -> Word16 #-}
203+{-# SPECIALIZE make_mask :: Int -> Word32 #-}
204+{-# SPECIALIZE make_mask :: Int -> Word64 #-}
205+
206+-- | Keep only the n least-significant bits of the given value
207+mask :: (Bits a, Num a) => Int -> a -> a
208+mask n v = v .&. make_mask n
209+{-# INLINE mask #-}
210+
211+-- | Bit order
212+--
213+-- E.g. two words of 5 bits: ABCDE, VWXYZ
214+-- - BB: ABCDEVWX YZxxxxxx
215+-- - LB: XYZABCDE xxxxxxVW
216+-- - BL: EDCBAZYX WVxxxxxx
217+-- - LL: XWVEDCBA xxxxxxZY
218+data BitOrder = BB | LB | BL | LL deriving (Show)
219+
220+-- | Reverse the @n@ least important bits of the given value
221+reverseBits :: (Num a, FastBits a, Bits a) => Int -> a -> a
222+reverseBits n value = rec value n 0
223+ where
224+ -- rec v i r, where
225+ -- v is orginal value shifted
226+ -- i is the remaining number of bits
227+ -- r is current value
228+ rec 0 0 r = r
229+ rec 0 i r = r `fastShiftL` i
230+ rec v i r = rec (v `fastShiftR` 1) (i-1) ((r `fastShiftL` 1) .|. (v .&. 0x1))
231+
180232-- | Read a single bit
181233readBool :: S -> Bool
182234readBool (S bs o bo) = case bo of
183235 BB -> testBit (unsafeHead bs) (7-o)
184236 BL -> testBit (unsafeHead bs) (7-o)
185− LL -> testBit (unsafeHead bs) o
186237 LB -> testBit (unsafeHead bs) o
187−
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)
193− LL -> testBit# o
194− LB -> testBit# o
195− where
196− !(W8# w) = unsafeHead bs
197− testBit# n = I# (((w `andWord8#` (wordToWord8# 1## `uncheckedShiftLWord8#` n)) `eqWord8#` wordToWord8# 0##) `xorI#` 1#)
198−
238+ LL -> testBit (unsafeHead bs) o
199239
200240-- | Extract a range of bits from (ws :: ByteString)
201241--
202242-- Constraint: 8 * (length ws -1 ) < o+n <= 8 * length ws
203−extract :: (Num a, FastBits a) => BitOrder -> ByteString -> Int -> Int -> a
243+extract :: (Num a, Bits a, FastBits a) => BitOrder -> ByteString -> Int -> Int -> a
204244extract bo bs o n
205245 | n == 0 = 0
206246 | B.length bs == 0 = error "Empty ByteString"
@@ -218,29 +258,36 @@ extract bo bs o n
218258
219259 -- shift offset depending on the byte position (0..B.length-1)
220260 off i = case bo of
221− LL -> 8*i - o
222261 LB -> 8*i - o
262+ LL -> 8*i - o
223263 BB -> (B.length bs -1 - i) * 8 - r
224264 BL -> (B.length bs -1 - i) * 8 - r
225265
226266 -- reverse bits if necessary
227267 rev = case bo of
228− LB -> reverseBits n
268+ LL -> reverseBits n
229269 BL -> reverseBits n
230− BB -> id
231− LL -> id
270+ BB -> id
271+ LB -> id
232272
233273
234274-- | Generic readWord
235−readWord :: (Num a, FastBits a) => Int -> S -> a
275+readWord :: (Num a, Bits a, FastBits a) => Int -> S -> a
236276readWord n (S bs o bo)
237277 | n == 0 = 0
238− | otherwise = extract bo (unsafeTake nbytes bs) o n
239− where nbytes = byte_offset (o+n+7)
278+ | o+n <= 8 = extract bo (unsafeTake 1 bs) o n
279+ | o+n <= 16 = extract bo (unsafeTake 2 bs) o n
280+ | o+n <= 24 = extract bo (unsafeTake 3 bs) o n
281+ | o+n <= 32 = extract bo (unsafeTake 4 bs) o n
282+ | o+n <= 40 = extract bo (unsafeTake 5 bs) o n
283+ | o+n <= 48 = extract bo (unsafeTake 6 bs) o n
284+ | o+n <= 56 = extract bo (unsafeTake 7 bs) o n
285+ | o+n <= 64 = extract bo (unsafeTake 8 bs) o n
286+ | otherwise = extract bo (unsafeTake ((o+n+7) `div` 8) bs) o n
240287
241288-- | Check that the number of bits to read is not greater than the first parameter
242289{-# INLINE readWordChecked #-}
243−readWordChecked :: (Num a, FastBits a) => Int -> Int -> S -> a
290+readWordChecked :: (Num a, Bits a, FastBits a) => Int -> Int -> S -> a
244291readWordChecked m n s
245292 | n > m = error $ "Tried to read more than " ++ show m ++ " bits (" ++ show n ++")"
246293 | otherwise = readWord n s
@@ -248,24 +295,23 @@ readWordChecked m n s
248295-- | Read the given number of bytes and return them in Big-Endian order
249296--
250297-- Examples:
251−-- BB: xxxABCDE FGHIJKLM NOPxxxxx -> ABCDEFGH IJKLMNOP
252−-- LL: LMNOPxxx DEFGHIJK xxxxxABC -> ABCDEFGH IJKLMNOP
253−-- BL: xxxPONML KJIHGFED CBAxxxxx -> ABCDEFGH IJKLMNOP
254−-- LB: EDCBAxxx MLKJIHGF xxxxxPON -> ABCDEFGH IJKLMNOP
298+-- BB: xxxABCDE FGHIJKLM NOPQRxxx -> ABCDEFGH IJKLMNOP QRxxxxxx
299+-- LB: NOPQRxxx FGHIJKLM xxxABCDE -> ABCDEFGH IJKLMNOP QRxxxxxx
300+-- BL: xxxRQPON MLKJIHGF EDCBAxxx -> ABCDEFGH IJKLMNOP QRxxxxxx
301+-- LL: EDCBAxxx MLKJIHGF xxxRQPON -> ABCDEFGH IJKLMNOP QRxxxxxx
255302readByteString :: Int -> S -> ByteString
256303readByteString n (S bs o bo) =
257304 let
258− bs' = unsafeTake (n+1) bs
259− bs'' = unsafeTake n bs
260− rev = B.map (reverseBits 8)
305+ bs' = unsafeTake (n+1) bs
306+ rev = B.map (reverseBits 9)
261307 in case (o,bo) of
262− (0,BB) -> bs''
263− (0,LL) -> B.reverse bs''
264− (0,LB) -> rev bs''
265− (0,BL) -> rev . B.reverse $ bs''
266− (_,LL) -> readByteString n (S (B.reverse bs') (8-o) BB)
267− (_,BL) -> rev . B.reverse $ readByteString n (S bs' o BB)
268− (_,LB) -> rev . B.reverse $ readByteString n (S bs' o LL)
308+ (0,BB) -> unsafeTake n bs
309+ (0,LB) -> B.reverse (unsafeTake n bs)
310+ (0,BL) -> rev (unsafeTake n bs)
311+ (0,LL) -> rev (B.reverse (unsafeTake n bs))
312+ (_,BL) -> rev (readByteString n (S (B.reverse bs') o LB))
313+ (_,LL) -> rev (readByteString n (S (B.reverse bs') o BB))
314+ (_,LB) -> readByteString n (S (B.reverse bs') o BB)
269315 (_,BB) -> unsafePerformIO $ do
270316 let len = n+1
271317 ptr <- mallocBytes len
@@ -287,6 +333,7 @@ newtype BitGet a = B { runState :: S -> Get (S,a) }
287333
288334instance Monad BitGet where
289335 return x = B $ \s -> return (s,x)
336+ fail str = B $ \s -> putBackState s >> fail str
290337 (B f) >>= g = B $ \s -> do (s',a) <- f s
291338 runState (g a) s'
292339
@@ -297,29 +344,6 @@ instance Applicative BitGet where
297344 pure x = return x
298345 fm <*> m = fm >>= \f -> m >>= \v -> return (f v)
299346
300−instance BitOrderable BitGet where
301− setBitOrder bo = do
302− (S bs o _) <- getState
303− putState (S bs o bo)
304−
305− getBitOrder = do
306− (S _ _ bo) <- getState
307− return bo
308−
309−instance Alignable BitGet where
310− -- | Skip the given number of bits
311− skipBits n = do
312− ensureBits n
313− withState (incS n)
314−
315− -- | Skip bits if necessary to align to the next byte
316− alignByte = do
317− (S _ o _) <- getState
318− when (o /= 0) $
319− skipBits (8-o)
320−
321−
322−
323347-- | Run a 'BitGet' within the Binary packages 'Get' monad. If a byte has
324348-- been partially consumed it will be discarded once 'runBitGet' is finished.
325349runBitGet :: BitGet a -> Get a
@@ -354,6 +378,13 @@ withState f = do
354378 s <- getState
355379 putState $! f s
356380
381+-- | Get the bit ordering
382+getBitOrder :: BitGet BitOrder
383+getBitOrder = do
384+ (S _ _ bo) <- getState
385+ return bo
386+
387+
357388-- | Make sure there are at least @n@ bits.
358389ensureBits :: Int -> BitGet ()
359390ensureBits n = do
@@ -367,6 +398,33 @@ ensureBits n = do
367398 put B.empty
368399 return (S (bs`append`bs') o bo, ())
369400
401+-- | Skip the given number of bits
402+skipBits :: Int -> BitGet ()
403+skipBits n = do
404+ ensureBits n
405+ withState (incS n)
406+
407+-- | Skip bits if necessary to align to the next byte
408+alignByte :: BitGet ()
409+alignByte = do
410+ (S _ o _) <- getState
411+ when (o /= 0) $
412+ skipBits (8-o)
413+
414+-- | Select the bit ordering
415+selectBitOrder :: BitOrder -> BitGet ()
416+selectBitOrder = withState . selectBitOrderS
417+
418+withBitOrder :: BitOrder -> BitGet a -> BitGet a
419+withBitOrder bo f = do
420+ bo' <- getBitOrder
421+ selectBitOrder bo
422+ r <- f
423+ selectBitOrder bo'
424+ return r
425+
426+
427+
370428-- | Test whether all input has been consumed, i.e. there are no remaining
371429-- undecoded bytes.
372430isEmpty :: BitGet Bool
@@ -378,10 +436,6 @@ isEmpty = B $ \ (S bs o bo) -> if B.null bs
378436getBool :: BitGet Bool
379437getBool = block bool
380438
381−-- | Get 1 bit as a 'Bool'.
382−getBool# :: BitGet Int
383−getBool# = block bool#
384−
385439-- | Get @n@ bits as a 'Word8'. @n@ must be within @[0..8]@.
386440getWord8 :: Int -> BitGet Word8
387441getWord8 n = block (word8 n)
@@ -457,10 +511,6 @@ block (Block i p) = do
457511bool :: Block Bool
458512bool = Block 1 readBool
459513
460−-- | Read a 1 bit 'Bool'.
461−bool# :: Block Int
462−bool# = Block 1 readBool#
463−
464514-- | Read @n@ bits as a 'Word8'. @n@ must be within @[0..8]@.
465515word8 :: Int -> Block Word8
466516word8 n = Block n (readWordChecked 8 n)
@@ -494,3 +544,84 @@ byteString :: Int -> Block ByteString
494544byteString n | n > 0 = Block (n*8) (readByteString n)
495545 | otherwise = Block 0 (\_ -> B.empty)
496546
547+
548+---------------------------------------------------------------------
549+-- Unchecked shifts, from the "binary" package
550+
551+-- | Class for types supporting fast bit shifting
552+class FastBits a where
553+ fastShiftR :: a -> Int -> a
554+ fastShiftL :: a -> Int -> a
555+
556+ {-# INLINE fastShift #-}
557+ fastShift :: a -> Int -> a
558+ fastShift x n
559+ | n > 0 = fastShiftL x n
560+ | n < 0 = fastShiftR x (negate n)
561+ | otherwise = x
562+
563+instance FastBits Word8 where
564+ fastShiftR = shiftr_w8
565+ fastShiftL = shiftl_w8
566+
567+instance FastBits Word16 where
568+ fastShiftR = shiftr_w16
569+ fastShiftL = shiftl_w16
570+
571+instance FastBits Word32 where
572+ fastShiftR = shiftr_w32
573+ fastShiftL = shiftl_w32
574+
575+instance FastBits Word64 where
576+ fastShiftR = shiftr_w64
577+ fastShiftL = shiftl_w64
578+
579+
580+shiftl_w8 :: Word8 -> Int -> Word8
581+shiftl_w16 :: Word16 -> Int -> Word16
582+shiftl_w32 :: Word32 -> Int -> Word32
583+shiftl_w64 :: Word64 -> Int -> Word64
584+
585+shiftr_w8 :: Word8 -> Int -> Word8
586+shiftr_w16 :: Word16 -> Int -> Word16
587+shiftr_w32 :: Word32 -> Int -> Word32
588+shiftr_w64 :: Word64 -> Int -> Word64
589+
590+#if defined(__GLASGOW_HASKELL__) && !defined(__HADDOCK__)
591+shiftl_w8 (W8# w) (I# i) = W8# (w `uncheckedShiftL#` i)
592+shiftl_w16 (W16# w) (I# i) = W16# (w `uncheckedShiftL#` i)
593+shiftl_w32 (W32# w) (I# i) = W32# (w `uncheckedShiftL#` i)
594+
595+shiftr_w8 (W8# w) (I# i) = W8# (w `uncheckedShiftRL#` i)
596+shiftr_w16 (W16# w) (I# i) = W16# (w `uncheckedShiftRL#` i)
597+shiftr_w32 (W32# w) (I# i) = W32# (w `uncheckedShiftRL#` i)
598+
599+
600+#if WORD_SIZE_IN_BITS < 64
601+shiftl_w64 (W64# w) (I# i) = W64# (w `uncheckedShiftL64#` i)
602+shiftr_w64 (W64# w) (I# i) = W64# (w `uncheckedShiftRL64#` i)
603+
604+#if __GLASGOW_HASKELL__ <= 606
605+-- Exported by GHC.Word in GHC 6.8 and higher
606+foreign import ccall unsafe "stg_uncheckedShiftL64"
607+ uncheckedShiftL64# :: Word64# -> Int# -> Word64#
608+foreign import ccall unsafe "stg_uncheckedShiftRL64"
609+ uncheckedShiftRL64# :: Word64# -> Int# -> Word64#
610+#endif
611+
612+#else
613+shiftl_w64 (W64# w) (I# i) = W64# (w `uncheckedShiftL#` i)
614+shiftr_w64 (W64# w) (I# i) = W64# (w `uncheckedShiftRL#` i)
615+#endif
616+
617+#else
618+shiftl_w8 = shiftL
619+shiftl_w16 = shiftL
620+shiftl_w32 = shiftL
621+shiftl_w64 = shiftL
622+
623+shiftr_w8 = shiftR
624+shiftr_w16 = shiftR
625+shiftr_w32 = shiftR
626+shiftr_w64 = shiftR
627+#endif