@@ -4,6 +4,7 @@
44-- |
55-- Module : Data.Binary.Bits.Get
66-- Copyright : (c) Lennart Kolmodin 2010-2011
7+-- (c) Sylvain Henry 2015
78-- License : BSD3-style (see LICENSE)
89--
910-- Maintainer : kolmodin@gmail.com
@@ -55,13 +56,11 @@ module Data.Binary.Bits.Get
5556 -- $bitget
5657
5758 BitGet
58− , BitOrder(..)
5959 , runBitGet
60− , selectBitOrder
61− , withBitOrder
6260
6361 -- ** Get bytes
6462 , getBool
63+ , getBool#
6564 , getWord8
6665 , getWord16
6766 , getWord32
@@ -98,6 +97,9 @@ module Data.Binary.Bits.Get
9897
9998import Data.Binary.Get as B ( Get, getLazyByteString, isEmpty )
10099import 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
101103
102104import Data.ByteString as B
103105import qualified Data.ByteString.Lazy as L
@@ -113,12 +115,8 @@ import Control.Applicative
113115import Control.Monad (when,foldM_)
114116
115117import Prelude as P
116−
117−#if defined(__GLASGOW_HASKELL__) && !defined(__HADDOCK__)
118−import GHC.Base
119118import GHC.Word
120−#endif
121−
119+import GHC.Base (uncheckedShiftLWord8#, wordToWord8#, Int (..), andWord8#, Word8#, (-#), Int#, xorI#, eqWord8#, TYPE)
122120
123121-- $bitget
124122-- Parse bits using a monad.
@@ -171,16 +169,6 @@ data S = S {-# UNPACK #-} !ByteString -- Input
171169 !BitOrder -- Bit order
172170 deriving (Show)
173171
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−
184172-- | Increment the current bit offset
185173incS :: Int -> S -> S
186174incS o (S bs n bo) = S (unsafeDrop d bs) n' bo
@@ -189,83 +177,70 @@ incS o (S bs n bo) = S (unsafeDrop d bs) n' bo
189177 !d = byte_offset o'
190178 !n' = bit_offset o'
191179
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 -- not implemented
217−-- - LL: XWVEDCBA xxxxxxZY -- not implemented
218−data BitOrder = BB | LB deriving (Show)
219−
220−
221180-- | Read a single bit
222181readBool :: S -> Bool
223182readBool (S bs o bo) = case bo of
224183 BB -> testBit (unsafeHead bs) (7-o)
184+ BL -> testBit (unsafeHead bs) (7-o)
185+ LL -> testBit (unsafeHead bs) o
225186 LB -> testBit (unsafeHead bs) o
226187
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+
199+
227200-- | Extract a range of bits from (ws :: ByteString)
228201--
229202-- Constraint: 8 * (length ws -1 ) < o+n <= 8 * length ws
230−extract :: (Num a, Bits a, FastBits a) => BitOrder -> ByteString -> Int -> Int -> a
203+extract :: (Num a, FastBits a) => BitOrder -> ByteString -> Int -> Int -> a
231204extract bo bs o n
232205 | n == 0 = 0
233206 | B.length bs == 0 = error "Empty ByteString"
234− | otherwise = mask n (foldlWithIndex' f 0 bs)
207+ | otherwise = rev . mask n . foldlWithIndex' f 0 $ bs
235208 where
236209 -- B.foldl' with index
237210 foldlWithIndex' op b = fst . B.foldl' g (b,0)
238211 where g (b',i) w = (op b' w i, (i+1))
239212
240213 -- 'or' correctly shifted words
241− f b w i = b .|. (fromIntegral w `fastShift` off i)
214+ f b w i = b .|. (fromIntegral w `fastShift` off i)
242215
243216 -- co-offset
244− r = B.length bs * 8 - (o + n)
217+ r = B.length bs * 8 - (o + n)
245218
246219 -- shift offset depending on the byte position (0..B.length-1)
247− off i = case bo of
220+ off i = case bo of
221+ LL -> 8*i - o
248222 LB -> 8*i - o
249223 BB -> (B.length bs -1 - i) * 8 - r
224+ BL -> (B.length bs -1 - i) * 8 - r
225+
226+ -- reverse bits if necessary
227+ rev = case bo of
228+ LB -> reverseBits n
229+ BL -> reverseBits n
230+ BB -> id
231+ LL -> id
250232
251233
252234-- | Generic readWord
253−readWord :: (Num a, Bits a, FastBits a) => Int -> S -> a
235+readWord :: (Num a, FastBits a) => Int -> S -> a
254236readWord n (S bs o bo)
255237 | n == 0 = 0
256− | o+n <= 8 = extract bo (unsafeTake 1 bs) o n
257− | o+n <= 16 = extract bo (unsafeTake 2 bs) o n
258− | o+n <= 24 = extract bo (unsafeTake 3 bs) o n
259− | o+n <= 32 = extract bo (unsafeTake 4 bs) o n
260− | o+n <= 40 = extract bo (unsafeTake 5 bs) o n
261− | o+n <= 48 = extract bo (unsafeTake 6 bs) o n
262− | o+n <= 56 = extract bo (unsafeTake 7 bs) o n
263− | o+n <= 64 = extract bo (unsafeTake 8 bs) o n
264− | otherwise = extract bo (unsafeTake ((o+n+7) `div` 8) bs) o n
238+ | otherwise = extract bo (unsafeTake nbytes bs) o n
239+ where nbytes = byte_offset (o+n+7)
265240
266241-- | Check that the number of bits to read is not greater than the first parameter
267242{-# INLINE readWordChecked #-}
268−readWordChecked :: (Num a, Bits a, FastBits a) => Int -> Int -> S -> a
243+readWordChecked :: (Num a, FastBits a) => Int -> Int -> S -> a
269244readWordChecked m n s
270245 | n > m = error $ "Tried to read more than " ++ show m ++ " bits (" ++ show n ++")"
271246 | otherwise = readWord n s
@@ -273,39 +248,37 @@ readWordChecked m n s
273248-- | Read the given number of bytes and return them in Big-Endian order
274249--
275250-- Examples:
276−-- BB: xxxABCDE FGHIJKLM NOPQRxxx -> ABCDEFGH IJKLMNOP QRxxxxxx
277−-- LB: NOPQRxxx FGHIJKLM xxxABCDE -> ABCDEFGH IJKLMNOP QRxxxxxx
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
278255readByteString :: Int -> S -> ByteString
279−readByteString n (S bs o bo)
280− | o == 0 = case bo of
281− BB -> unsafeTake n bs
282− LB -> B.reverse (unsafeTake n bs)
283−
284− | otherwise = unsafePerformIO $ do
285− let len = n+1
286− ptr <- mallocBytes len
287− case bo of
288− BB -> do
289− let f r i = do
290− let
291− w = unsafeIndex bs (len-i)
292− w' = (w `fastShiftL` o) .|. r
293− r' = w `fastShiftR` (8-o)
294− poke (ptr `plusPtr` (len-i)) w'
295− return r'
296− foldM_ f 0 [1..len]
297− unsafeInit <$> unsafePackMallocCStringLen (ptr,len)
298−
299− LB -> do
300− let f r i = do
301− let
302− w = unsafeIndex bs (i-1)
303− w' = (w `fastShiftL` (8-o)) .|. r
304− r' = w `fastShiftR` o
305− poke (ptr `plusPtr` (len-i)) w'
306− return r'
307− foldM_ f 0 [1..len]
308− unsafeTail <$> unsafePackMallocCStringLen (ptr,len)
256+readByteString n (S bs o bo) =
257+ let
258+ bs' = unsafeTake (n+1) bs
259+ bs'' = unsafeTake n bs
260+ rev = B.map (reverseBits 8)
261+ 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)
269+ (_,BB) -> unsafePerformIO $ do
270+ let len = n+1
271+ ptr <- mallocBytes len
272+ let f r i = do
273+ let
274+ w = unsafeIndex bs (len-i)
275+ w' = (w `fastShiftL` o) .|. r
276+ r' = w `fastShiftR` (8-o)
277+ poke (ptr `plusPtr` (len-i)) w'
278+ return r'
279+ foldM_ f 0 [1..len]
280+ unsafeInit <$> unsafePackMallocCStringLen (ptr,len)
281+
309282
310283------------------------------------------------------------------------
311284-- | 'BitGet' is a monad, applicative and a functor. See 'runBitGet'
@@ -314,7 +287,6 @@ newtype BitGet a = B { runState :: S -> Get (S,a) }
314287
315288instance Monad BitGet where
316289 return x = B $ \s -> return (s,x)
317− fail str = B $ \s -> putBackState s >> fail str
318290 (B f) >>= g = B $ \s -> do (s',a) <- f s
319291 runState (g a) s'
320292
@@ -325,6 +297,29 @@ instance Applicative BitGet where
325297 pure x = return x
326298 fm <*> m = fm >>= \f -> m >>= \v -> return (f v)
327299
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+
328323-- | Run a 'BitGet' within the Binary packages 'Get' monad. If a byte has
329324-- been partially consumed it will be discarded once 'runBitGet' is finished.
330325runBitGet :: BitGet a -> Get a
@@ -359,13 +354,6 @@ withState f = do
359354 s <- getState
360355 putState $! f s
361356
362−-- | Get the bit ordering
363−getBitOrder :: BitGet BitOrder
364−getBitOrder = do
365− (S _ _ bo) <- getState
366− return bo
367−
368−
369357-- | Make sure there are at least @n@ bits.
370358ensureBits :: Int -> BitGet ()
371359ensureBits n = do
@@ -379,33 +367,6 @@ ensureBits n = do
379367 put B.empty
380368 return (S (bs`append`bs') o bo, ())
381369
382−-- | Skip the given number of bits
383−skipBits :: Int -> BitGet ()
384−skipBits n = do
385− ensureBits n
386− withState (incS n)
387−
388−-- | Skip bits if necessary to align to the next byte
389−alignByte :: BitGet ()
390−alignByte = do
391− (S _ o _) <- getState
392− when (o /= 0) $
393− skipBits (8-o)
394−
395−-- | Select the bit ordering
396−selectBitOrder :: BitOrder -> BitGet ()
397−selectBitOrder = withState . selectBitOrderS
398−
399−withBitOrder :: BitOrder -> BitGet a -> BitGet a
400−withBitOrder bo f = do
401− bo' <- getBitOrder
402− selectBitOrder bo
403− r <- f
404− selectBitOrder bo'
405− return r
406−
407−
408−
409370-- | Test whether all input has been consumed, i.e. there are no remaining
410371-- undecoded bytes.
411372isEmpty :: BitGet Bool
@@ -417,6 +378,10 @@ isEmpty = B $ \ (S bs o bo) -> if B.null bs
417378getBool :: BitGet Bool
418379getBool = block bool
419380
381+-- | Get 1 bit as a 'Bool'.
382+getBool# :: BitGet Int
383+getBool# = block bool#
384+
420385-- | Get @n@ bits as a 'Word8'. @n@ must be within @[0..8]@.
421386getWord8 :: Int -> BitGet Word8
422387getWord8 n = block (word8 n)
@@ -492,6 +457,10 @@ block (Block i p) = do
492457bool :: Block Bool
493458bool = Block 1 readBool
494459
460+-- | Read a 1 bit 'Bool'.
461+bool# :: Block Int
462+bool# = Block 1 readBool#
463+
495464-- | Read @n@ bits as a 'Word8'. @n@ must be within @[0..8]@.
496465word8 :: Int -> Block Word8
497466word8 n = Block n (readWordChecked 8 n)
@@ -525,84 +494,3 @@ byteString :: Int -> Block ByteString
525494byteString n | n > 0 = Block (n*8) (readByteString n)
526495 | otherwise = Block 0 (\_ -> B.empty)
527496
528−
529−---------------------------------------------------------------------
530−-- Unchecked shifts, from the "binary" package
531−
532−-- | Class for types supporting fast bit shifting
533−class FastBits a where
534− fastShiftR :: a -> Int -> a
535− fastShiftL :: a -> Int -> a
536−
537− {-# INLINE fastShift #-}
538− fastShift :: a -> Int -> a
539− fastShift x n
540− | n > 0 = fastShiftL x n
541− | n < 0 = fastShiftR x (negate n)
542− | otherwise = x
543−
544−instance FastBits Word8 where
545− fastShiftR = shiftr_w8
546− fastShiftL = shiftl_w8
547−
548−instance FastBits Word16 where
549− fastShiftR = shiftr_w16
550− fastShiftL = shiftl_w16
551−
552−instance FastBits Word32 where
553− fastShiftR = shiftr_w32
554− fastShiftL = shiftl_w32
555−
556−instance FastBits Word64 where
557− fastShiftR = shiftr_w64
558− fastShiftL = shiftl_w64
559−
560−
561−shiftl_w8 :: Word8 -> Int -> Word8
562−shiftl_w16 :: Word16 -> Int -> Word16
563−shiftl_w32 :: Word32 -> Int -> Word32
564−shiftl_w64 :: Word64 -> Int -> Word64
565−
566−shiftr_w8 :: Word8 -> Int -> Word8
567−shiftr_w16 :: Word16 -> Int -> Word16
568−shiftr_w32 :: Word32 -> Int -> Word32
569−shiftr_w64 :: Word64 -> Int -> Word64
570−
571−#if defined(__GLASGOW_HASKELL__) && !defined(__HADDOCK__)
572−shiftl_w8 (W8# w) (I# i) = W8# (w `uncheckedShiftL#` i)
573−shiftl_w16 (W16# w) (I# i) = W16# (w `uncheckedShiftL#` i)
574−shiftl_w32 (W32# w) (I# i) = W32# (w `uncheckedShiftL#` i)
575−
576−shiftr_w8 (W8# w) (I# i) = W8# (w `uncheckedShiftRL#` i)
577−shiftr_w16 (W16# w) (I# i) = W16# (w `uncheckedShiftRL#` i)
578−shiftr_w32 (W32# w) (I# i) = W32# (w `uncheckedShiftRL#` i)
579−
580−
581−#if WORD_SIZE_IN_BITS < 64
582−shiftl_w64 (W64# w) (I# i) = W64# (w `uncheckedShiftL64#` i)
583−shiftr_w64 (W64# w) (I# i) = W64# (w `uncheckedShiftRL64#` i)
584−
585−#if __GLASGOW_HASKELL__ <= 606
586−-- Exported by GHC.Word in GHC 6.8 and higher
587−foreign import ccall unsafe "stg_uncheckedShiftL64"
588− uncheckedShiftL64# :: Word64# -> Int# -> Word64#
589−foreign import ccall unsafe "stg_uncheckedShiftRL64"
590− uncheckedShiftRL64# :: Word64# -> Int# -> Word64#
591−#endif
592−
593−#else
594−shiftl_w64 (W64# w) (I# i) = W64# (w `uncheckedShiftL#` i)
595−shiftr_w64 (W64# w) (I# i) = W64# (w `uncheckedShiftRL#` i)
596−#endif
597−
598−#else
599−shiftl_w8 = shiftL
600−shiftl_w16 = shiftL
601−shiftl_w32 = shiftL
602−shiftl_w64 = shiftL
603−
604−shiftr_w8 = shiftR
605−shiftr_w16 = shiftR
606−shiftr_w32 = shiftR
607−shiftr_w64 = shiftR
608−#endif