@@ -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,12 @@ module Data.Binary.Bits.Get
56 -- $bitget
55 -- $bitget
59 , runBitGet
59 , runBitGet
61 -- ** Get bytes
62 -- ** Get bytes
64 , getWord8
64 , getWord8
65 , getWord16
65 , getWord16
66 , getWord32
66 , getWord32
@@ -97,9 +97,6 @@ module Data.Binary.Bits.Get
98import Data.Binary.Get as B ( Get, getLazyByteString, isEmpty )
98import Data.Binary.Get as B ( Get, getLazyByteString, isEmpty )
99import Data.Binary.Get.Internal as B ( get, put, ensureN )
99import 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
101import Data.ByteString as B
105import qualified Data.ByteString.Lazy as L
102import qualified Data.ByteString.Lazy as L
@@ -115,8 +112,12 @@ import Control.Applicative
115import Control.Monad (when,foldM_)
112import Control.Monad (when,foldM_)
117import Prelude as P
114import Prelude as P
116+#if defined(__GLASGOW_HASKELL__) && !defined(__HADDOCK__)
118import GHC.Word
118import GHC.Word
119−import GHC.Base (uncheckedShiftLWord8#, wordToWord8#, Int (..), andWord8#, Word8#, (-#), Int#, xorI#, eqWord8#, TYPE)
119+#endif
121-- $bitget
122-- $bitget
122-- Parse bits using a monad.
123-- Parse bits using a monad.
@@ -169,6 +170,16 @@ data S = S {-# UNPACK #-} !ByteString -- Input
169 !BitOrder -- Bit order
170 !BitOrder -- Bit order
170 deriving (Show)
171 deriving (Show)
173+-- | Compute bit offset (equivalent to x `mod` 8 but faster)
174+bit_offset :: Int -> Int
175+bit_offset n = make_mask 3 .&. n
176+{-# INLINE bit_offset #-}
178+-- | Compute byte offset (equivalent to x `div` 8 but faster)
179+byte_offset :: Int -> Int
180+byte_offset n = n `shiftR` 3
181+{-# INLINE byte_offset #-}
172-- | Increment the current bit offset
183-- | Increment the current bit offset
173incS :: Int -> S -> S
184incS :: Int -> S -> S
174incS o (S bs n bo) = S (unsafeDrop d bs) n' bo
185incS o (S bs n bo) = S (unsafeDrop d bs) n' bo
@@ -177,70 +188,83 @@ incS o (S bs n bo) = S (unsafeDrop d bs) n' bo
177 !d = byte_offset o'
188 !d = byte_offset o'
178 !n' = bit_offset o'
189 !n' = bit_offset o'
191+-- | Select the bit ordering
192+selectBitOrderS :: BitOrder -> S -> S
193+selectBitOrderS bo (S bs o _) = S bs o bo
195+-- | make_mask 3 = 00000111
196+make_mask :: (Bits a, Num a) => Int -> a
197+make_mask n = (1 `shiftL` fromIntegral n) - 1
198+{-# SPECIALIZE make_mask :: Int -> Int #-}
199+{-# SPECIALIZE make_mask :: Int -> Word #-}
200+{-# SPECIALIZE make_mask :: Int -> Word8 #-}
201+{-# SPECIALIZE make_mask :: Int -> Word16 #-}
202+{-# SPECIALIZE make_mask :: Int -> Word32 #-}
203+{-# SPECIALIZE make_mask :: Int -> Word64 #-}
205+-- | Keep only the n least-significant bits of the given value
206+mask :: (Bits a, Num a) => Int -> a -> a
207+mask n v = v .&. make_mask n
212+-- E.g. two words of 5 bits: ABCDE, VWXYZ
213+-- - BB: ABCDEVWX YZxxxxxx
214+-- - LB: XYZABCDE xxxxxxVW
215+-- - BL: EDCBAZYX WVxxxxxx -- not implemented
216+-- - LL: XWVEDCBA xxxxxxZY -- not implemented
217+data BitOrder = BB | LB deriving (Show)
180-- | Read a single bit
220-- | Read a single bit
181readBool :: S -> Bool
221readBool :: S -> Bool
182readBool (S bs o bo) = case bo of
222readBool (S bs o bo) = case bo of
183 BB -> testBit (unsafeHead bs) (7-o)
223 BB -> testBit (unsafeHead bs) (7-o)
184− BL -> testBit (unsafeHead bs) (7-o)
185− LL -> testBit (unsafeHead bs) o
186 LB -> testBit (unsafeHead bs) o
224 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
197− testBit# n = I# (((w `andWord8#` (wordToWord8# 1## `uncheckedShiftLWord8#` n)) `eqWord8#` wordToWord8# 0##) `xorI#` 1#)
200-- | Extract a range of bits from (ws :: ByteString)
226-- | Extract a range of bits from (ws :: ByteString)
202-- Constraint: 8 * (length ws -1 ) < o+n <= 8 * length ws
228-- Constraint: 8 * (length ws -1 ) < o+n <= 8 * length ws
203−extract :: (Num a, FastBits a) => BitOrder -> ByteString -> Int -> Int -> a
229+extract :: (Num a, Bits a, FastBits a) => BitOrder -> ByteString -> Int -> Int -> a
204extract bo bs o n
230extract bo bs o n
205 | n == 0 = 0
231 | n == 0 = 0
206 | B.length bs == 0 = error "Empty ByteString"
232 | B.length bs == 0 = error "Empty ByteString"
207− | otherwise = rev . mask n . foldlWithIndex' f 0 $ bs
233+ | otherwise = mask n (foldlWithIndex' f 0 bs)
209 -- B.foldl' with index
235 -- B.foldl' with index
210 foldlWithIndex' op b = fst . B.foldl' g (b,0)
236 foldlWithIndex' op b = fst . B.foldl' g (b,0)
211 where g (b',i) w = (op b' w i, (i+1))
237 where g (b',i) w = (op b' w i, (i+1))
213 -- 'or' correctly shifted words
239 -- 'or' correctly shifted words
214− f b w i = b .|. (fromIntegral w `fastShift` off i)
240+ f b w i = b .|. (fromIntegral w `fastShift` off i)
216 -- co-offset
242 -- co-offset
217− r = B.length bs * 8 - (o + n)
243+ r = B.length bs * 8 - (o + n)
219 -- shift offset depending on the byte position (0..B.length-1)
245 -- shift offset depending on the byte position (0..B.length-1)
220− off i = case bo of
246+ off i = case bo of
222 LB -> 8*i - o
247 LB -> 8*i - o
223 BB -> (B.length bs -1 - i) * 8 - r
248 BB -> (B.length bs -1 - i) * 8 - r
224− BL -> (B.length bs -1 - i) * 8 - r
226− -- reverse bits if necessary
234-- | Generic readWord
251-- | Generic readWord
235−readWord :: (Num a, FastBits a) => Int -> S -> a
252+readWord :: (Num a, Bits a, FastBits a) => Int -> S -> a
236readWord n (S bs o bo)
253readWord n (S bs o bo)
237 | n == 0 = 0
254 | n == 0 = 0
255+ | o+n <= 8 = extract bo (unsafeTake 1 bs) o n
256+ | o+n <= 16 = extract bo (unsafeTake 2 bs) o n
257+ | o+n <= 24 = extract bo (unsafeTake 3 bs) o n
258+ | o+n <= 32 = extract bo (unsafeTake 4 bs) o n
259+ | o+n <= 40 = extract bo (unsafeTake 5 bs) o n
260+ | o+n <= 48 = extract bo (unsafeTake 6 bs) o n
261+ | o+n <= 56 = extract bo (unsafeTake 7 bs) o n
262+ | o+n <= 64 = extract bo (unsafeTake 8 bs) o n
238− | otherwise = extract bo (unsafeTake nbytes bs) o n
263+ | otherwise = extract bo (unsafeTake ((o+n+7) `div` 8) bs) o n
239− where nbytes = byte_offset (o+n+7)
241-- | Check that the number of bits to read is not greater than the first parameter
265-- | Check that the number of bits to read is not greater than the first parameter
242{-# INLINE readWordChecked #-}
266{-# INLINE readWordChecked #-}
243−readWordChecked :: (Num a, FastBits a) => Int -> Int -> S -> a
267+readWordChecked :: (Num a, Bits a, FastBits a) => Int -> Int -> S -> a
244readWordChecked m n s
268readWordChecked m n s
245 | n > m = error $ "Tried to read more than " ++ show m ++ " bits (" ++ show n ++")"
269 | n > m = error $ "Tried to read more than " ++ show m ++ " bits (" ++ show n ++")"
246 | otherwise = readWord n s
270 | otherwise = readWord n s
@@ -248,37 +272,36 @@ readWordChecked m n s
248-- | Read the given number of bytes and return them in Big-Endian order
272-- | Read the given number of bytes and return them in Big-Endian order
250-- Examples:
274-- Examples:
251−-- BB: xxxABCDE FGHIJKLM NOPxxxxx -> ABCDEFGH IJKLMNOP
275+-- BB: xxxABCDE FGHIJKLM NOPQRxxx -> ABCDEFGH IJKLMNOP QRxxxxxx
252−-- LL: LMNOPxxx DEFGHIJK xxxxxABC -> ABCDEFGH IJKLMNOP
276+-- LB: NOPQRxxx FGHIJKLM xxxABCDE -> ABCDEFGH IJKLMNOP QRxxxxxx
253−-- BL: xxxPONML KJIHGFED CBAxxxxx -> ABCDEFGH IJKLMNOP
254−-- LB: EDCBAxxx MLKJIHGF xxxxxPON -> ABCDEFGH IJKLMNOP
255readByteString :: Int -> S -> ByteString
277readByteString :: Int -> S -> ByteString
256−readByteString n (S bs o bo) =
278+readByteString n (S bs o bo)
258− bs' = unsafeTake (n+1) bs
259− bs'' = unsafeTake n bs
279+ | o == 0 = unsafeTake n bs
260− rev = B.map (reverseBits 8)
263− (0,LL) -> B.reverse 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)
269− (_,BB) -> unsafePerformIO $ do
280+ | otherwise = unsafePerformIO $ do
270− let len = n+1
281+ let len = n+1
271− ptr <- mallocBytes len
282+ ptr <- mallocBytes len
272− let f r i = do
285+ let f r i = do
274− w = unsafeIndex bs (len-i)
287+ w = unsafeIndex bs (len-i)
275− w' = (w `fastShiftL` o) .|. r
288+ w' = (w `fastShiftL` o) .|. r
276− r' = w `fastShiftR` (8-o)
289+ r' = w `fastShiftR` (8-o)
277− poke (ptr `plusPtr` (len-i)) w'
290+ poke (ptr `plusPtr` (len-i)) w'
278− return r'
291+ return r'
279− foldM_ f 0 [1..len]
292+ foldM_ f 0 [1..len]
280− unsafeInit <$> unsafePackMallocCStringLen (ptr,len)
293+ unsafeInit <$> unsafePackMallocCStringLen (ptr,len)
298+ w = unsafeIndex bs (i-1)
299+ w' = (w `fastShiftL` (8-o)) .|. r
300+ r' = w `fastShiftR` o
301+ poke (ptr `plusPtr` (len-i)) w'
304+ unsafeTail <$> unsafePackMallocCStringLen (ptr,len)
283------------------------------------------------------------------------
306------------------------------------------------------------------------
284-- | 'BitGet' is a monad, applicative and a functor. See 'runBitGet'
307-- | 'BitGet' is a monad, applicative and a functor. See 'runBitGet'
@@ -287,6 +310,7 @@ newtype BitGet a = B { runState :: S -> Get (S,a) }
288instance Monad BitGet where
311instance Monad BitGet where
289 return x = B $ \s -> return (s,x)
312 return x = B $ \s -> return (s,x)
313+ fail str = B $ \s -> putBackState s >> fail str
290 (B f) >>= g = B $ \s -> do (s',a) <- f s
314 (B f) >>= g = B $ \s -> do (s',a) <- f s
291 runState (g a) s'
315 runState (g a) s'
@@ -297,29 +321,6 @@ instance Applicative BitGet where
297 pure x = return x
321 pure x = return x
298 fm <*> m = fm >>= \f -> m >>= \v -> return (f v)
322 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
324-- | 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.
325-- been partially consumed it will be discarded once 'runBitGet' is finished.
325runBitGet :: BitGet a -> Get a
326runBitGet :: BitGet a -> Get a
@@ -367,6 +368,23 @@ ensureBits n = do
367 put B.empty
368 put B.empty
368 return (S (bs`append`bs') o bo, ())
369 return (S (bs`append`bs') o bo, ())
371+-- | Skip the given number of bits
372+skipBits :: Int -> BitGet ()
377+-- | Skip bits if necessary to align to the next byte
378+alignByte :: BitGet ()
380+ (S _ o _) <- getState
384+-- | Select the bit ordering
385+selectBitOrder :: BitOrder -> BitGet ()
386+selectBitOrder = withState . selectBitOrderS
370-- | Test whether all input has been consumed, i.e. there are no remaining
388-- | Test whether all input has been consumed, i.e. there are no remaining
371-- undecoded bytes.
389-- undecoded bytes.
372isEmpty :: BitGet Bool
390isEmpty :: BitGet Bool
@@ -378,10 +396,6 @@ isEmpty = B $ \ (S bs o bo) -> if B.null bs
378getBool :: BitGet Bool
396getBool :: BitGet Bool
379getBool = block bool
397getBool = 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]@.
399-- | Get @n@ bits as a 'Word8'. @n@ must be within @[0..8]@.
386getWord8 :: Int -> BitGet Word8
400getWord8 :: Int -> BitGet Word8
387getWord8 n = block (word8 n)
401getWord8 n = block (word8 n)
@@ -457,10 +471,6 @@ block (Block i p) = do
457bool :: Block Bool
471bool :: Block Bool
458bool = Block 1 readBool
472bool = 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]@.
474-- | Read @n@ bits as a 'Word8'. @n@ must be within @[0..8]@.
465word8 :: Int -> Block Word8
475word8 :: Int -> Block Word8
466word8 n = Block n (readWordChecked 8 n)
476word8 n = Block n (readWordChecked 8 n)
@@ -494,3 +504,84 @@ byteString :: Int -> Block ByteString
494byteString n | n > 0 = Block (n*8) (readByteString n)
504byteString n | n > 0 = Block (n*8) (readByteString n)
495 | otherwise = Block 0 (\_ -> B.empty)
505 | otherwise = Block 0 (\_ -> B.empty)
508+---------------------------------------------------------------------
509+-- Unchecked shifts, from the "binary" package
511+-- | Class for types supporting fast bit shifting
512+class FastBits a where
513+ fastShiftR :: a -> Int -> a
514+ fastShiftL :: a -> Int -> a
516+ {-# INLINE fastShift #-}
517+ fastShift :: a -> Int -> a
519+ | n > 0 = fastShiftL x n
520+ | n < 0 = fastShiftR x (negate n)
523+instance FastBits Word8 where
524+ fastShiftR = shiftr_w8
525+ fastShiftL = shiftl_w8
527+instance FastBits Word16 where
528+ fastShiftR = shiftr_w16
529+ fastShiftL = shiftl_w16
531+instance FastBits Word32 where
532+ fastShiftR = shiftr_w32
533+ fastShiftL = shiftl_w32
535+instance FastBits Word64 where
536+ fastShiftR = shiftr_w64
537+ fastShiftL = shiftl_w64
540+shiftl_w8 :: Word8 -> Int -> Word8
541+shiftl_w16 :: Word16 -> Int -> Word16
542+shiftl_w32 :: Word32 -> Int -> Word32
543+shiftl_w64 :: Word64 -> Int -> Word64
545+shiftr_w8 :: Word8 -> Int -> Word8
546+shiftr_w16 :: Word16 -> Int -> Word16
547+shiftr_w32 :: Word32 -> Int -> Word32
548+shiftr_w64 :: Word64 -> Int -> Word64
550+#if defined(__GLASGOW_HASKELL__) && !defined(__HADDOCK__)
551+shiftl_w8 (W8# w) (I# i) = W8# (w `uncheckedShiftL#` i)
552+shiftl_w16 (W16# w) (I# i) = W16# (w `uncheckedShiftL#` i)
553+shiftl_w32 (W32# w) (I# i) = W32# (w `uncheckedShiftL#` i)
555+shiftr_w8 (W8# w) (I# i) = W8# (w `uncheckedShiftRL#` i)
556+shiftr_w16 (W16# w) (I# i) = W16# (w `uncheckedShiftRL#` i)
557+shiftr_w32 (W32# w) (I# i) = W32# (w `uncheckedShiftRL#` i)
560+#if WORD_SIZE_IN_BITS < 64
561+shiftl_w64 (W64# w) (I# i) = W64# (w `uncheckedShiftL64#` i)
562+shiftr_w64 (W64# w) (I# i) = W64# (w `uncheckedShiftRL64#` i)
564+#if __GLASGOW_HASKELL__ <= 606
565+-- Exported by GHC.Word in GHC 6.8 and higher
566+foreign import ccall unsafe "stg_uncheckedShiftL64"
567+ uncheckedShiftL64# :: Word64# -> Int# -> Word64#
568+foreign import ccall unsafe "stg_uncheckedShiftRL64"
569+ uncheckedShiftRL64# :: Word64# -> Int# -> Word64#
573+shiftl_w64 (W64# w) (I# i) = W64# (w `uncheckedShiftL#` i)
574+shiftr_w64 (W64# w) (I# i) = W64# (w `uncheckedShiftRL#` i)