{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE Trustworthy #-}

{-# OPTIONS_HADDOCK not-home #-}

-----------------------------------------------------------------------------
-- |
-- Module      :  GHC.Bits
-- Copyright   :  (c) The University of Glasgow 2001
-- License     :  BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer  :  libraries@haskell.org
-- Stability   :  stable
-- Portability :  portable
--
-- This module defines bitwise operations for signed and unsigned
-- integers.  Instances of the class 'Bits' for the 'Int' and
-- 'Integer' types are available from this module, and instances for
-- explicitly sized integral types are available from the
-- "Data.Int" and "Data.Word" modules.
--
-----------------------------------------------------------------------------

module GHC.Bits (
  Bits(
    (.&.), (.|.), xor,
    complement,
    shift,
    rotate,
    zeroBits,
    bit,
    setBit,
    clearBit,
    complementBit,
    testBit,
    bitSizeMaybe,
    bitSize,
    isSigned,
    shiftL, shiftR,
    unsafeShiftL, unsafeShiftR,
    rotateL, rotateR,
    popCount
  ),
  FiniteBits(
    finiteBitSize,
    countLeadingZeros,
    countTrailingZeros
  ),

  bitDefault,
  testBitDefault,
  popCountDefault,
  toIntegralSized,
 ) where

-- Defines the @Bits@ class containing bit-based operations.
-- See library document for details on the semantics of the
-- individual operations.

#include "MachDeps.h"

import Data.Maybe
import GHC.Num
import GHC.Base
import GHC.Real

infixl 8 `shift`, `rotate`, `shiftL`, `shiftR`, `rotateL`, `rotateR`
infixl 7 .&.
infixl 6 `xor`
infixl 5 .|.

{-# DEPRECATED bitSize "Use 'bitSizeMaybe' or 'finiteBitSize' instead" #-} -- deprecated in 7.8

-- | The 'Bits' class defines bitwise operations over integral types.
--
-- * Bits are numbered from 0 with bit 0 being the least
--   significant bit.
class Eq a => Bits a where
    {-# MINIMAL (.&.), (.|.), xor, complement,
                (shift | (shiftL, shiftR)),
                (rotate | (rotateL, rotateR)),
                bitSize, bitSizeMaybe, isSigned, testBit, bit, popCount #-}

    -- | Bitwise \"and\"
    (.&.) :: a -> a -> a

    -- | Bitwise \"or\"
    (.|.) :: a -> a -> a

    -- | Bitwise \"xor\"
    xor :: a -> a -> a

    {-| Reverse all the bits in the argument -}
    complement        :: a -> a

    {-| @'shift' x i@ shifts @x@ left by @i@ bits if @i@ is positive,
        or right by @-i@ bits otherwise.
        Right shifts perform sign extension on signed number types;
        i.e. they fill the top bits with 1 if the @x@ is negative
        and with 0 otherwise.

        An instance can define either this unified 'shift' or 'shiftL' and
        'shiftR', depending on which is more convenient for the type in
        question. -}
    shift             :: a -> Int -> a

    a
x `shift`   Int
i | Int
iInt -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<Int
0       = a
x a -> Int -> a
forall a. Bits a => a -> Int -> a
`shiftR` (-Int
i)
                  | Int
iInt -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>Int
0       = a
x a -> Int -> a
forall a. Bits a => a -> Int -> a
`shiftL` Int
i
                  | Bool
otherwise = a
x

    {-| @'rotate' x i@ rotates @x@ left by @i@ bits if @i@ is positive,
        or right by @-i@ bits otherwise.

        For unbounded types like 'Integer', 'rotate' is equivalent to 'shift'.

        An instance can define either this unified 'rotate' or 'rotateL' and
        'rotateR', depending on which is more convenient for the type in
        question. -}
    rotate            :: a -> Int -> a

    a
x `rotate`  Int
i | Int
iInt -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<Int
0       = a
x a -> Int -> a
forall a. Bits a => a -> Int -> a
`rotateR` (-Int
i)
                  | Int
iInt -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>Int
0       = a
x a -> Int -> a
forall a. Bits a => a -> Int -> a
`rotateL` Int
i
                  | Bool
otherwise = a
x

    {-
    -- Rotation can be implemented in terms of two shifts, but care is
    -- needed for negative values.  This suggested implementation assumes
    -- 2's-complement arithmetic.  It is commented out because it would
    -- require an extra context (Ord a) on the signature of 'rotate'.
    x `rotate`  i | i<0 && isSigned x && x<0
                         = let left = i+bitSize x in
                           ((x `shift` i) .&. complement ((-1) `shift` left))
                           .|. (x `shift` left)
                  | i<0  = (x `shift` i) .|. (x `shift` (i+bitSize x))
                  | i==0 = x
                  | i>0  = (x `shift` i) .|. (x `shift` (i-bitSize x))
    -}

    -- | 'zeroBits' is the value with all bits unset.
    --
    -- The following laws ought to hold (for all valid bit indices @/n/@):
    --
    --   * @'clearBit' 'zeroBits' /n/ == 'zeroBits'@
    --   * @'setBit'   'zeroBits' /n/ == 'bit' /n/@
    --   * @'testBit'  'zeroBits' /n/ == False@
    --   * @'popCount' 'zeroBits'   == 0@
    --
    -- This method uses @'clearBit' ('bit' 0) 0@ as its default
    -- implementation (which ought to be equivalent to 'zeroBits' for
    -- types which possess a 0th bit).
    --
    -- @since 4.7.0.0
    zeroBits :: a
    zeroBits = a -> Int -> a
forall a. Bits a => a -> Int -> a
clearBit (Int -> a
forall a. Bits a => Int -> a
bit Int
0) Int
0

    -- | @bit /i/@ is a value with the @/i/@th bit set and all other bits clear.
    --
    -- Can be implemented using `bitDefault' if @a@ is also an
    -- instance of 'Num'.
    --
    -- See also 'zeroBits'.
    bit               :: Int -> a

    -- | @x \`setBit\` i@ is the same as @x .|. bit i@
    setBit            :: a -> Int -> a

    -- | @x \`clearBit\` i@ is the same as @x .&. complement (bit i)@
    clearBit          :: a -> Int -> a

    -- | @x \`complementBit\` i@ is the same as @x \`xor\` bit i@
    complementBit     :: a -> Int -> a

    {-| @x \`testBit\` i@ is the same as @x .&. bit n /= 0@

        In other words it returns True if the bit at offset @n
        is set.

        Can be implemented using `testBitDefault' if @a@ is also an
        instance of 'Num'.
        -}
    testBit           :: a -> Int -> Bool

    {-| Return the number of bits in the type of the argument.  The actual
        value of the argument is ignored.  Returns Nothing
        for types that do not have a fixed bitsize, like 'Integer'.

        @since 4.7.0.0
        -}
    bitSizeMaybe      :: a -> Maybe Int

    {-| Return the number of bits in the type of the argument.  The actual
        value of the argument is ignored.  The function 'bitSize' is
        undefined for types that do not have a fixed bitsize, like 'Integer'.

        Default implementation based upon 'bitSizeMaybe' provided since
        4.12.0.0.
        -}
    bitSize           :: a -> Int
    bitSize a
b = Int -> Maybe Int -> Int
forall a. a -> Maybe a -> a
fromMaybe ([Char] -> Int
forall a. HasCallStack => [Char] -> a
error [Char]
"bitSize is undefined") (a -> Maybe Int
forall a. Bits a => a -> Maybe Int
bitSizeMaybe a
b)

    {-| Return 'True' if the argument is a signed type.  The actual
        value of the argument is ignored -}
    isSigned          :: a -> Bool

    {-# INLINE setBit #-}
    {-# INLINE clearBit #-}
    {-# INLINE complementBit #-}
    a
x `setBit` Int
i        = a
x a -> a -> a
forall a. Bits a => a -> a -> a
.|. Int -> a
forall a. Bits a => Int -> a
bit Int
i
    a
x `clearBit` Int
i      = a
x a -> a -> a
forall a. Bits a => a -> a -> a
.&. a -> a
forall a. Bits a => a -> a
complement (Int -> a
forall a. Bits a => Int -> a
bit Int
i)
    a
x `complementBit` Int
i = a
x a -> a -> a
forall a. Bits a => a -> a -> a
`xor` Int -> a
forall a. Bits a => Int -> a
bit Int
i

    {-| Shift the argument left by the specified number of bits
        (which must be non-negative). Some instances may throw an
        'Control.Exception.Overflow' exception if given a negative input.

        An instance can define either this and 'shiftR' or the unified
        'shift', depending on which is more convenient for the type in
        question. -}
    shiftL            :: a -> Int -> a
    {-# INLINE shiftL #-}
    a
x `shiftL`  Int
i = a
x a -> Int -> a
forall a. Bits a => a -> Int -> a
`shift`  Int
i

    {-| Shift the argument left by the specified number of bits.  The
        result is undefined for negative shift amounts and shift amounts
        greater or equal to the 'bitSize'.

        Defaults to 'shiftL' unless defined explicitly by an instance.

        @since 4.5.0.0 -}
    unsafeShiftL            :: a -> Int -> a
    {-# INLINE unsafeShiftL #-}
    a
x `unsafeShiftL` Int
i = a
x a -> Int -> a
forall a. Bits a => a -> Int -> a
`shiftL` Int
i

    {-| Shift the first argument right by the specified number of bits. The
        result is undefined for negative shift amounts and shift amounts
        greater or equal to the 'bitSize'. Some instances may throw an
        'Control.Exception.Overflow' exception if given a negative input.

        Right shifts perform sign extension on signed number types;
        i.e. they fill the top bits with 1 if the @x@ is negative
        and with 0 otherwise.

        An instance can define either this and 'shiftL' or the unified
        'shift', depending on which is more convenient for the type in
        question. -}
    shiftR            :: a -> Int -> a
    {-# INLINE shiftR #-}
    a
x `shiftR`  Int
i = a
x a -> Int -> a
forall a. Bits a => a -> Int -> a
`shift`  (-Int
i)

    {-| Shift the first argument right by the specified number of bits, which
        must be non-negative and smaller than the number of bits in the type.

        Right shifts perform sign extension on signed number types;
        i.e. they fill the top bits with 1 if the @x@ is negative
        and with 0 otherwise.

        Defaults to 'shiftR' unless defined explicitly by an instance.

        @since 4.5.0.0 -}
    unsafeShiftR            :: a -> Int -> a
    {-# INLINE unsafeShiftR #-}
    a
x `unsafeShiftR` Int
i = a
x a -> Int -> a
forall a. Bits a => a -> Int -> a
`shiftR` Int
i

    {-| Rotate the argument left by the specified number of bits
        (which must be non-negative).

        An instance can define either this and 'rotateR' or the unified
        'rotate', depending on which is more convenient for the type in
        question. -}
    rotateL           :: a -> Int -> a
    {-# INLINE rotateL #-}
    a
x `rotateL` Int
i = a
x a -> Int -> a
forall a. Bits a => a -> Int -> a
`rotate` Int
i

    {-| Rotate the argument right by the specified number of bits
        (which must be non-negative).

        An instance can define either this and 'rotateL' or the unified
        'rotate', depending on which is more convenient for the type in
        question. -}
    rotateR           :: a -> Int -> a
    {-# INLINE rotateR #-}
    a
x `rotateR` Int
i = a
x a -> Int -> a
forall a. Bits a => a -> Int -> a
`rotate` (-Int
i)

    {-| Return the number of set bits in the argument.  This number is
        known as the population count or the Hamming weight.

        Can be implemented using `popCountDefault' if @a@ is also an
        instance of 'Num'.

        @since 4.5.0.0 -}
    popCount          :: a -> Int

-- |The 'FiniteBits' class denotes types with a finite, fixed number of bits.
--
-- @since 4.7.0.0
class Bits b => FiniteBits b where
    -- | Return the number of bits in the type of the argument.
    -- The actual value of the argument is ignored. Moreover, 'finiteBitSize'
    -- is total, in contrast to the deprecated 'bitSize' function it replaces.
    --
    -- @
    -- 'finiteBitSize' = 'bitSize'
    -- 'bitSizeMaybe' = 'Just' . 'finiteBitSize'
    -- @
    --
    -- @since 4.7.0.0
    finiteBitSize :: b -> Int

    -- | Count number of zero bits preceding the most significant set bit.
    --
    -- @
    -- 'countLeadingZeros' ('zeroBits' :: a) = finiteBitSize ('zeroBits' :: a)
    -- @
    --
    -- 'countLeadingZeros' can be used to compute log base 2 via
    --
    -- @
    -- logBase2 x = 'finiteBitSize' x - 1 - 'countLeadingZeros' x
    -- @
    --
    -- Note: The default implementation for this method is intentionally
    -- naive. However, the instances provided for the primitive
    -- integral types are implemented using CPU specific machine
    -- instructions.
    --
    -- @since 4.8.0.0
    countLeadingZeros :: b -> Int
    countLeadingZeros b
x = (Int
wInt -> Int -> Int
forall a. Num a => a -> a -> a
-Int
1) Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int -> Int
go (Int
wInt -> Int -> Int
forall a. Num a => a -> a -> a
-Int
1)
      where
        go :: Int -> Int
go Int
i | Int
i Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
0       = Int
i -- no bit set
             | b -> Int -> Bool
forall a. Bits a => a -> Int -> Bool
testBit b
x Int
i = Int
i
             | Bool
otherwise   = Int -> Int
go (Int
iInt -> Int -> Int
forall a. Num a => a -> a -> a
-Int
1)

        w :: Int
w = b -> Int
forall b. FiniteBits b => b -> Int
finiteBitSize b
x

    -- | Count number of zero bits following the least significant set bit.
    --
    -- @
    -- 'countTrailingZeros' ('zeroBits' :: a) = finiteBitSize ('zeroBits' :: a)
    -- 'countTrailingZeros' . 'negate' = 'countTrailingZeros'
    -- @
    --
    -- The related
    -- <http://en.wikipedia.org/wiki/Find_first_set find-first-set operation>
    -- can be expressed in terms of 'countTrailingZeros' as follows
    --
    -- @
    -- findFirstSet x = 1 + 'countTrailingZeros' x
    -- @
    --
    -- Note: The default implementation for this method is intentionally
    -- naive. However, the instances provided for the primitive
    -- integral types are implemented using CPU specific machine
    -- instructions.
    --
    -- @since 4.8.0.0
    countTrailingZeros :: b -> Int
    countTrailingZeros b
x = Int -> Int
go Int
0
      where
        go :: Int -> Int
go Int
i | Int
i Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
w      = Int
i
             | b -> Int -> Bool
forall a. Bits a => a -> Int -> Bool
testBit b
x Int
i = Int
i
             | Bool
otherwise   = Int -> Int
go (Int
iInt -> Int -> Int
forall a. Num a => a -> a -> a
+Int
1)

        w :: Int
w = b -> Int
forall b. FiniteBits b => b -> Int
finiteBitSize b
x


-- The defaults below are written with lambdas so that e.g.
--     bit = bitDefault
-- is fully applied, so inlining will happen

-- | Default implementation for 'bit'.
--
-- Note that: @bitDefault i = 1 `shiftL` i@
--
-- @since 4.6.0.0
bitDefault :: (Bits a, Num a) => Int -> a
bitDefault :: forall a. (Bits a, Num a) => Int -> a
bitDefault = \Int
i -> a
1 a -> Int -> a
forall a. Bits a => a -> Int -> a
`shiftL` Int
i
{-# INLINE bitDefault #-}

-- | Default implementation for 'testBit'.
--
-- Note that: @testBitDefault x i = (x .&. bit i) /= 0@
--
-- @since 4.6.0.0
testBitDefault ::  (Bits a, Num a) => a -> Int -> Bool
testBitDefault :: forall a. (Bits a, Num a) => a -> Int -> Bool
testBitDefault = \a
x Int
i -> (a
x a -> a -> a
forall a. Bits a => a -> a -> a
.&. Int -> a
forall a. Bits a => Int -> a
bit Int
i) a -> a -> Bool
forall a. Eq a => a -> a -> Bool
/= a
0
{-# INLINE testBitDefault #-}

-- | Default implementation for 'popCount'.
--
-- This implementation is intentionally naive. Instances are expected to provide
-- an optimized implementation for their size.
--
-- @since 4.6.0.0
popCountDefault :: (Bits a, Num a) => a -> Int
popCountDefault :: forall a. (Bits a, Num a) => a -> Int
popCountDefault = Int -> a -> Int
forall {t} {t}. (Num t, Num t, Bits t) => t -> t -> t
go Int
0
 where
   go :: t -> t -> t
go !t
c t
0 = t
c
   go t
c t
w = t -> t -> t
go (t
ct -> t -> t
forall a. Num a => a -> a -> a
+t
1) (t
w t -> t -> t
forall a. Bits a => a -> a -> a
.&. (t
w t -> t -> t
forall a. Num a => a -> a -> a
- t
1)) -- clear the least significant
{-# INLINABLE popCountDefault #-}

-- | Interpret 'Bool' as 1-bit bit-field
--
--  @since 4.7.0.0
instance Bits Bool where
    .&. :: Bool -> Bool -> Bool
(.&.) = Bool -> Bool -> Bool
(&&)

    .|. :: Bool -> Bool -> Bool
(.|.) = Bool -> Bool -> Bool
(||)

    xor :: Bool -> Bool -> Bool
xor = Bool -> Bool -> Bool
forall a. Eq a => a -> a -> Bool
(/=)

    complement :: Bool -> Bool
complement = Bool -> Bool
not

    shift :: Bool -> Int -> Bool
shift Bool
x Int
0 = Bool
x
    shift Bool
_ Int
_ = Bool
False

    rotate :: Bool -> Int -> Bool
rotate Bool
x Int
_ = Bool
x

    bit :: Int -> Bool
bit Int
0 = Bool
True
    bit Int
_ = Bool
False

    testBit :: Bool -> Int -> Bool
testBit Bool
x Int
0 = Bool
x
    testBit Bool
_ Int
_ = Bool
False

    bitSizeMaybe :: Bool -> Maybe Int
bitSizeMaybe Bool
_ = Int -> Maybe Int
forall a. a -> Maybe a
Just Int
1

    bitSize :: Bool -> Int
bitSize Bool
_ = Int
1

    isSigned :: Bool -> Bool
isSigned Bool
_ = Bool
False

    popCount :: Bool -> Int
popCount Bool
False = Int
0
    popCount Bool
True  = Int
1

-- | @since 4.7.0.0
instance FiniteBits Bool where
    finiteBitSize :: Bool -> Int
finiteBitSize Bool
_ = Int
1
    countTrailingZeros :: Bool -> Int
countTrailingZeros Bool
x = if Bool
x then Int
0 else Int
1
    countLeadingZeros :: Bool -> Int
countLeadingZeros  Bool
x = if Bool
x then Int
0 else Int
1

-- | @since 2.01
instance Bits Int where
    {-# INLINE shift #-}
    {-# INLINE bit #-}
    {-# INLINE testBit #-}
    -- We want popCnt# to be inlined in user code so that `ghc -msse4.2`
    -- can compile it down to a popcnt instruction without an extra function call
    {-# INLINE popCount #-}

    zeroBits :: Int
zeroBits = Int
0

    bit :: Int -> Int
bit     = Int -> Int
forall a. (Bits a, Num a) => Int -> a
bitDefault

    testBit :: Int -> Int -> Bool
testBit = Int -> Int -> Bool
forall a. (Bits a, Num a) => a -> Int -> Bool
testBitDefault

    (I# Int#
x#) .&. :: Int -> Int -> Int
.&.   (I# Int#
y#)          = Int# -> Int
I# (Int#
x# Int# -> Int# -> Int#
`andI#` Int#
y#)
    (I# Int#
x#) .|. :: Int -> Int -> Int
.|.   (I# Int#
y#)          = Int# -> Int
I# (Int#
x# Int# -> Int# -> Int#
`orI#`  Int#
y#)
    (I# Int#
x#) xor :: Int -> Int -> Int
`xor` (I# Int#
y#)          = Int# -> Int
I# (Int#
x# Int# -> Int# -> Int#
`xorI#` Int#
y#)
    complement :: Int -> Int
complement (I# Int#
x#)             = Int# -> Int
I# (Int# -> Int#
notI# Int#
x#)
    (I# Int#
x#) shift :: Int -> Int -> Int
`shift` (I# Int#
i#)
        | Int# -> Bool
isTrue# (Int#
i# Int# -> Int# -> Int#
>=# Int#
0#)      = Int# -> Int
I# (Int#
x# Int# -> Int# -> Int#
`iShiftL#` Int#
i#)
        | Bool
otherwise                = Int# -> Int
I# (Int#
x# Int# -> Int# -> Int#
`iShiftRA#` Int# -> Int#
negateInt# Int#
i#)
    (I# Int#
x#) shiftL :: Int -> Int -> Int
`shiftL` (I# Int#
i#)
        | Int# -> Bool
isTrue# (Int#
i# Int# -> Int# -> Int#
>=# Int#
0#)      = Int# -> Int
I# (Int#
x# Int# -> Int# -> Int#
`iShiftL#` Int#
i#)
        | Bool
otherwise                = Int
forall a. a
overflowError
    (I# Int#
x#) unsafeShiftL :: Int -> Int -> Int
`unsafeShiftL` (I# Int#
i#) = Int# -> Int
I# (Int#
x# Int# -> Int# -> Int#
`uncheckedIShiftL#` Int#
i#)
    (I# Int#
x#) shiftR :: Int -> Int -> Int
`shiftR` (I# Int#
i#)
        | Int# -> Bool
isTrue# (Int#
i# Int# -> Int# -> Int#
>=# Int#
0#)      = Int# -> Int
I# (Int#
x# Int# -> Int# -> Int#
`iShiftRA#` Int#
i#)
        | Bool
otherwise                = Int
forall a. a
overflowError
    (I# Int#
x#) unsafeShiftR :: Int -> Int -> Int
`unsafeShiftR` (I# Int#
i#) = Int# -> Int
I# (Int#
x# Int# -> Int# -> Int#
`uncheckedIShiftRA#` Int#
i#)

    {-# INLINE rotate #-}       -- See Note [Constant folding for rotate]
    (I# Int#
x#) rotate :: Int -> Int -> Int
`rotate` (I# Int#
i#) =
        Int# -> Int
I# ((Int#
x# Int# -> Int# -> Int#
`uncheckedIShiftL#` Int#
i'#) Int# -> Int# -> Int#
`orI#` (Int#
x# Int# -> Int# -> Int#
`uncheckedIShiftRL#` (Int#
wsib Int# -> Int# -> Int#
-# Int#
i'#)))
      where
        !i'# :: Int#
i'# = Int#
i# Int# -> Int# -> Int#
`andI#` (Int#
wsib Int# -> Int# -> Int#
-# Int#
1#)
        !wsib :: Int#
wsib = WORD_SIZE_IN_BITS#   {- work around preprocessor problem (??) -}
    bitSizeMaybe :: Int -> Maybe Int
bitSizeMaybe Int
i         = Int -> Maybe Int
forall a. a -> Maybe a
Just (Int -> Int
forall b. FiniteBits b => b -> Int
finiteBitSize Int
i)
    bitSize :: Int -> Int
bitSize Int
i              = Int -> Int
forall b. FiniteBits b => b -> Int
finiteBitSize Int
i

    popCount :: Int -> Int
popCount (I# Int#
x#) = Int# -> Int
I# (Word# -> Int#
word2Int# (Word# -> Word#
popCnt# (Int# -> Word#
int2Word# Int#
x#)))

    isSigned :: Int -> Bool
isSigned Int
_             = Bool
True

-- | @since 4.6.0.0
instance FiniteBits Int where
    finiteBitSize :: Int -> Int
finiteBitSize Int
_ = WORD_SIZE_IN_BITS
    countLeadingZeros :: Int -> Int
countLeadingZeros  (I# Int#
x#) = Int# -> Int
I# (Word# -> Int#
word2Int# (Word# -> Word#
clz# (Int# -> Word#
int2Word# Int#
x#)))
    {-# INLINE countLeadingZeros #-}
    countTrailingZeros :: Int -> Int
countTrailingZeros (I# Int#
x#) = Int# -> Int
I# (Word# -> Int#
word2Int# (Word# -> Word#
ctz# (Int# -> Word#
int2Word# Int#
x#)))
    {-# INLINE countTrailingZeros #-}

-- | @since 2.01
instance Bits Word where
    {-# INLINE shift #-}
    {-# INLINE bit #-}
    {-# INLINE testBit #-}
    {-# INLINE popCount #-}

    (W# Word#
x#) .&. :: Word -> Word -> Word
.&.   (W# Word#
y#)    = Word# -> Word
W# (Word#
x# Word# -> Word# -> Word#
`and#` Word#
y#)
    (W# Word#
x#) .|. :: Word -> Word -> Word
.|.   (W# Word#
y#)    = Word# -> Word
W# (Word#
x# Word# -> Word# -> Word#
`or#`  Word#
y#)
    (W# Word#
x#) xor :: Word -> Word -> Word
`xor` (W# Word#
y#)    = Word# -> Word
W# (Word#
x# Word# -> Word# -> Word#
`xor#` Word#
y#)
    complement :: Word -> Word
complement (W# Word#
x#)       = Word# -> Word
W# (Word# -> Word#
not# Word#
x#)
    (W# Word#
x#) shift :: Word -> Int -> Word
`shift` (I# Int#
i#)
        | Int# -> Bool
isTrue# (Int#
i# Int# -> Int# -> Int#
>=# Int#
0#)      = Word# -> Word
W# (Word#
x# Word# -> Int# -> Word#
`shiftL#` Int#
i#)
        | Bool
otherwise                = Word# -> Word
W# (Word#
x# Word# -> Int# -> Word#
`shiftRL#` Int# -> Int#
negateInt# Int#
i#)
    (W# Word#
x#) shiftL :: Word -> Int -> Word
`shiftL` (I# Int#
i#)
        | Int# -> Bool
isTrue# (Int#
i# Int# -> Int# -> Int#
>=# Int#
0#)      = Word# -> Word
W# (Word#
x# Word# -> Int# -> Word#
`shiftL#` Int#
i#)
        | Bool
otherwise                = Word
forall a. a
overflowError
    (W# Word#
x#) unsafeShiftL :: Word -> Int -> Word
`unsafeShiftL` (I# Int#
i#) = Word# -> Word
W# (Word#
x# Word# -> Int# -> Word#
`uncheckedShiftL#` Int#
i#)
    (W# Word#
x#) shiftR :: Word -> Int -> Word
`shiftR` (I# Int#
i#)
        | Int# -> Bool
isTrue# (Int#
i# Int# -> Int# -> Int#
>=# Int#
0#)      = Word# -> Word
W# (Word#
x# Word# -> Int# -> Word#
`shiftRL#` Int#
i#)
        | Bool
otherwise                = Word
forall a. a
overflowError
    (W# Word#
x#) unsafeShiftR :: Word -> Int -> Word
`unsafeShiftR` (I# Int#
i#) = Word# -> Word
W# (Word#
x# Word# -> Int# -> Word#
`uncheckedShiftRL#` Int#
i#)
    (W# Word#
x#) rotate :: Word -> Int -> Word
`rotate` (I# Int#
i#)
        | Int# -> Bool
isTrue# (Int#
i'# Int# -> Int# -> Int#
==# Int#
0#) = Word# -> Word
W# Word#
x#
        | Bool
otherwise  = Word# -> Word
W# ((Word#
x# Word# -> Int# -> Word#
`uncheckedShiftL#` Int#
i'#) Word# -> Word# -> Word#
`or#` (Word#
x# Word# -> Int# -> Word#
`uncheckedShiftRL#` (Int#
wsib Int# -> Int# -> Int#
-# Int#
i'#)))
        where
        !i'# :: Int#
i'# = Int#
i# Int# -> Int# -> Int#
`andI#` (Int#
wsib Int# -> Int# -> Int#
-# Int#
1#)
        !wsib :: Int#
wsib = WORD_SIZE_IN_BITS#  {- work around preprocessor problem (??) -}
    bitSizeMaybe :: Word -> Maybe Int
bitSizeMaybe Word
i           = Int -> Maybe Int
forall a. a -> Maybe a
Just (Word -> Int
forall b. FiniteBits b => b -> Int
finiteBitSize Word
i)
    bitSize :: Word -> Int
bitSize Word
i                = Word -> Int
forall b. FiniteBits b => b -> Int
finiteBitSize Word
i
    isSigned :: Word -> Bool
isSigned Word
_               = Bool
False
    popCount :: Word -> Int
popCount (W# Word#
x#)         = Int# -> Int
I# (Word# -> Int#
word2Int# (Word# -> Word#
popCnt# Word#
x#))
    bit :: Int -> Word
bit                      = Int -> Word
forall a. (Bits a, Num a) => Int -> a
bitDefault
    testBit :: Word -> Int -> Bool
testBit                  = Word -> Int -> Bool
forall a. (Bits a, Num a) => a -> Int -> Bool
testBitDefault

-- | @since 4.6.0.0
instance FiniteBits Word where
    finiteBitSize :: Word -> Int
finiteBitSize Word
_ = WORD_SIZE_IN_BITS
    countLeadingZeros :: Word -> Int
countLeadingZeros  (W# Word#
x#) = Int# -> Int
I# (Word# -> Int#
word2Int# (Word# -> Word#
clz# Word#
x#))
    {-# INLINE countLeadingZeros #-}
    countTrailingZeros :: Word -> Int
countTrailingZeros (W# Word#
x#) = Int# -> Int
I# (Word# -> Int#
word2Int# (Word# -> Word#
ctz# Word#
x#))
    {-# INLINE countTrailingZeros #-}

-- | @since 2.01
instance Bits Integer where
   .&. :: Integer -> Integer -> Integer
(.&.)      = Integer -> Integer -> Integer
integerAnd
   .|. :: Integer -> Integer -> Integer
(.|.)      = Integer -> Integer -> Integer
integerOr
   xor :: Integer -> Integer -> Integer
xor        = Integer -> Integer -> Integer
integerXor
   complement :: Integer -> Integer
complement = Integer -> Integer
integerComplement
   unsafeShiftR :: Integer -> Int -> Integer
unsafeShiftR Integer
x Int
i = Integer -> Word -> Integer
integerShiftR Integer
x (Int -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
i)
   unsafeShiftL :: Integer -> Int -> Integer
unsafeShiftL Integer
x Int
i = Integer -> Word -> Integer
integerShiftL Integer
x (Int -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
i)
   shiftR :: Integer -> Int -> Integer
shiftR Integer
x i :: Int
i@(I# Int#
i#)
      | Int# -> Bool
isTrue# (Int#
i# Int# -> Int# -> Int#
>=# Int#
0#) = Integer -> Int -> Integer
forall a. Bits a => a -> Int -> a
unsafeShiftR Integer
x Int
i
      | Bool
otherwise           = Integer
forall a. a
overflowError
   shiftL :: Integer -> Int -> Integer
shiftL Integer
x i :: Int
i@(I# Int#
i#)
      | Int# -> Bool
isTrue# (Int#
i# Int# -> Int# -> Int#
>=# Int#
0#) = Integer -> Int -> Integer
forall a. Bits a => a -> Int -> a
unsafeShiftL Integer
x Int
i
      | Bool
otherwise           = Integer
forall a. a
overflowError
   shift :: Integer -> Int -> Integer
shift Integer
x Int
i | Int
i Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
0    = Integer -> Word -> Integer
integerShiftL Integer
x (Int -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
i)
             | Bool
otherwise = Integer -> Word -> Integer
integerShiftR Integer
x (Int -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Int -> Int
forall a. Num a => a -> a
negate Int
i))
   testBit :: Integer -> Int -> Bool
testBit Integer
x Int
i = Integer -> Word -> Bool
integerTestBit Integer
x (Int -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
i)
   zeroBits :: Integer
zeroBits    = Integer
integerZero

   bit :: Int -> Integer
bit (I# Int#
i)  = Word# -> Integer
integerBit# (Int# -> Word#
int2Word# Int#
i)
   popCount :: Integer -> Int
popCount Integer
x  = Int# -> Int
I# (Integer -> Int#
integerPopCount# Integer
x)

   rotate :: Integer -> Int -> Integer
rotate Integer
x Int
i = Integer -> Int -> Integer
forall a. Bits a => a -> Int -> a
shift Integer
x Int
i   -- since an Integer never wraps around

   bitSizeMaybe :: Integer -> Maybe Int
bitSizeMaybe Integer
_ = Maybe Int
forall a. Maybe a
Nothing
   bitSize :: Integer -> Int
bitSize Integer
_  = [Char] -> Int
forall a. [Char] -> a
errorWithoutStackTrace [Char]
"Data.Bits.bitSize(Integer)"
   isSigned :: Integer -> Bool
isSigned Integer
_ = Bool
True

-- | @since 4.8.0
instance Bits Natural where
   .&. :: Natural -> Natural -> Natural
(.&.)         = Natural -> Natural -> Natural
naturalAnd
   .|. :: Natural -> Natural -> Natural
(.|.)         = Natural -> Natural -> Natural
naturalOr
   xor :: Natural -> Natural -> Natural
xor           = Natural -> Natural -> Natural
naturalXor
   complement :: Natural -> Natural
complement Natural
_  = [Char] -> Natural
forall a. [Char] -> a
errorWithoutStackTrace
                    [Char]
"Bits.complement: Natural complement undefined"
   unsafeShiftR :: Natural -> Int -> Natural
unsafeShiftR Natural
x Int
i = Natural -> Word -> Natural
naturalShiftR Natural
x (Int -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
i)
   unsafeShiftL :: Natural -> Int -> Natural
unsafeShiftL Natural
x Int
i = Natural -> Word -> Natural
naturalShiftL Natural
x (Int -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
i)
   shiftR :: Natural -> Int -> Natural
shiftR Natural
x i :: Int
i@(I# Int#
i#)
      | Int# -> Bool
isTrue# (Int#
i# Int# -> Int# -> Int#
>=# Int#
0#) = Natural -> Int -> Natural
forall a. Bits a => a -> Int -> a
unsafeShiftR Natural
x Int
i
      | Bool
otherwise           = Natural
forall a. a
overflowError
   shiftL :: Natural -> Int -> Natural
shiftL Natural
x i :: Int
i@(I# Int#
i#)
      | Int# -> Bool
isTrue# (Int#
i# Int# -> Int# -> Int#
>=# Int#
0#) = Natural -> Int -> Natural
forall a. Bits a => a -> Int -> a
unsafeShiftL Natural
x Int
i
      | Bool
otherwise           = Natural
forall a. a
overflowError
   shift :: Natural -> Int -> Natural
shift Natural
x Int
i
     | Int
i Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
0    = Natural -> Word -> Natural
naturalShiftL Natural
x (Int -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
i)
     | Bool
otherwise = Natural -> Word -> Natural
naturalShiftR Natural
x (Int -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Int -> Int
forall a. Num a => a -> a
negate Int
i))
   testBit :: Natural -> Int -> Bool
testBit Natural
x Int
i   = Natural -> Word -> Bool
naturalTestBit Natural
x (Int -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
i)
   zeroBits :: Natural
zeroBits      = Natural
naturalZero
   clearBit :: Natural -> Int -> Natural
clearBit Natural
x Int
i  = Natural
x Natural -> Natural -> Natural
forall a. Bits a => a -> a -> a
`xor` (Int -> Natural
forall a. Bits a => Int -> a
bit Int
i Natural -> Natural -> Natural
forall a. Bits a => a -> a -> a
.&. Natural
x)

   bit :: Int -> Natural
bit (I# Int#
i)  = Word# -> Natural
naturalBit# (Int# -> Word#
int2Word# Int#
i)
   popCount :: Natural -> Int
popCount Natural
x  = Int# -> Int
I# (Word# -> Int#
word2Int# (Natural -> Word#
naturalPopCount# Natural
x))

   rotate :: Natural -> Int -> Natural
rotate Natural
x Int
i = Natural -> Int -> Natural
forall a. Bits a => a -> Int -> a
shift Natural
x Int
i   -- since an Natural never wraps around

   bitSizeMaybe :: Natural -> Maybe Int
bitSizeMaybe Natural
_ = Maybe Int
forall a. Maybe a
Nothing
   bitSize :: Natural -> Int
bitSize Natural
_  = [Char] -> Int
forall a. [Char] -> a
errorWithoutStackTrace [Char]
"Data.Bits.bitSize(Natural)"
   isSigned :: Natural -> Bool
isSigned Natural
_ = Bool
False

-----------------------------------------------------------------------------

-- | Attempt to convert an 'Integral' type @a@ to an 'Integral' type @b@ using
-- the size of the types as measured by 'Bits' methods.
--
-- A simpler version of this function is:
--
-- > toIntegral :: (Integral a, Integral b) => a -> Maybe b
-- > toIntegral x
-- >   | toInteger x == toInteger y = Just y
-- >   | otherwise                  = Nothing
-- >   where
-- >     y = fromIntegral x
--
-- This version requires going through 'Integer', which can be inefficient.
-- However, @toIntegralSized@ is optimized to allow GHC to statically determine
-- the relative type sizes (as measured by 'bitSizeMaybe' and 'isSigned') and
-- avoid going through 'Integer' for many types. (The implementation uses
-- 'fromIntegral', which is itself optimized with rules for @base@ types but may
-- go through 'Integer' for some type pairs.)
--
-- @since 4.8.0.0

toIntegralSized :: (Integral a, Integral b, Bits a, Bits b) => a -> Maybe b
toIntegralSized :: forall a b.
(Integral a, Integral b, Bits a, Bits b) =>
a -> Maybe b
toIntegralSized a
x                 -- See Note [toIntegralSized optimization]
  | Bool -> (a -> Bool) -> Maybe a -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
True (a -> a -> Bool
forall a. Ord a => a -> a -> Bool
<= a
x) Maybe a
yMinBound
  , Bool -> (a -> Bool) -> Maybe a -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
True (a
x a -> a -> Bool
forall a. Ord a => a -> a -> Bool
<=) Maybe a
yMaxBound = b -> Maybe b
forall a. a -> Maybe a
Just b
y
  | Bool
otherwise                   = Maybe b
forall a. Maybe a
Nothing
  where
    y :: b
y = a -> b
forall a b. (Integral a, Num b) => a -> b
fromIntegral a
x

    xWidth :: Maybe Int
xWidth = a -> Maybe Int
forall a. Bits a => a -> Maybe Int
bitSizeMaybe a
x
    yWidth :: Maybe Int
yWidth = b -> Maybe Int
forall a. Bits a => a -> Maybe Int
bitSizeMaybe b
y

    yMinBound :: Maybe a
yMinBound
      | a -> b -> Bool
forall a b. (Bits a, Bits b) => a -> b -> Bool
isBitSubType a
x b
y = Maybe a
forall a. Maybe a
Nothing
      | a -> Bool
forall a. Bits a => a -> Bool
isSigned a
x, Bool -> Bool
not (b -> Bool
forall a. Bits a => a -> Bool
isSigned b
y) = a -> Maybe a
forall a. a -> Maybe a
Just a
0
      | a -> Bool
forall a. Bits a => a -> Bool
isSigned a
x, b -> Bool
forall a. Bits a => a -> Bool
isSigned b
y
      , Just Int
yW <- Maybe Int
yWidth = a -> Maybe a
forall a. a -> Maybe a
Just (a -> a
forall a. Num a => a -> a
negate (a -> a) -> a -> a
forall a b. (a -> b) -> a -> b
$ Int -> a
forall a. Bits a => Int -> a
bit (Int
yWInt -> Int -> Int
forall a. Num a => a -> a -> a
-Int
1)) -- Assumes sub-type
      | Bool
otherwise = Maybe a
forall a. Maybe a
Nothing

    yMaxBound :: Maybe a
yMaxBound
      | a -> b -> Bool
forall a b. (Bits a, Bits b) => a -> b -> Bool
isBitSubType a
x b
y = Maybe a
forall a. Maybe a
Nothing
      | a -> Bool
forall a. Bits a => a -> Bool
isSigned a
x, Bool -> Bool
not (b -> Bool
forall a. Bits a => a -> Bool
isSigned b
y)
      , Just Int
xW <- Maybe Int
xWidth, Just Int
yW <- Maybe Int
yWidth
      , Int
xW Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
yWInt -> Int -> Int
forall a. Num a => a -> a -> a
+Int
1 = Maybe a
forall a. Maybe a
Nothing -- Max bound beyond a's domain
      | Just Int
yW <- Maybe Int
yWidth = if b -> Bool
forall a. Bits a => a -> Bool
isSigned b
y
                            then a -> Maybe a
forall a. a -> Maybe a
Just (Int -> a
forall a. Bits a => Int -> a
bit (Int
yWInt -> Int -> Int
forall a. Num a => a -> a -> a
-Int
1)a -> a -> a
forall a. Num a => a -> a -> a
-a
1)
                            else a -> Maybe a
forall a. a -> Maybe a
Just (Int -> a
forall a. Bits a => Int -> a
bit Int
yWa -> a -> a
forall a. Num a => a -> a -> a
-a
1)
      | Bool
otherwise = Maybe a
forall a. Maybe a
Nothing
{-# INLINABLE toIntegralSized #-}

-- | 'True' if the size of @a@ is @<=@ the size of @b@, where size is measured
-- by 'bitSizeMaybe' and 'isSigned'.
isBitSubType :: (Bits a, Bits b) => a -> b -> Bool
isBitSubType :: forall a b. (Bits a, Bits b) => a -> b -> Bool
isBitSubType a
x b
y
  -- Reflexive
  | Maybe Int
xWidth Maybe Int -> Maybe Int -> Bool
forall a. Eq a => a -> a -> Bool
== Maybe Int
yWidth, Bool
xSigned Bool -> Bool -> Bool
forall a. Eq a => a -> a -> Bool
== Bool
ySigned = Bool
True

  -- Every integer is a subset of 'Integer'
  | Bool
ySigned, Maybe Int
forall a. Maybe a
Nothing Maybe Int -> Maybe Int -> Bool
forall a. Eq a => a -> a -> Bool
== Maybe Int
yWidth                  = Bool
True
  | Bool -> Bool
not Bool
xSigned, Bool -> Bool
not Bool
ySigned, Maybe Int
forall a. Maybe a
Nothing Maybe Int -> Maybe Int -> Bool
forall a. Eq a => a -> a -> Bool
== Maybe Int
yWidth = Bool
True

  -- Sub-type relations between fixed-with types
  | Bool
xSigned Bool -> Bool -> Bool
forall a. Eq a => a -> a -> Bool
== Bool
ySigned,   Just Int
xW <- Maybe Int
xWidth, Just Int
yW <- Maybe Int
yWidth = Int
xW Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
yW
  | Bool -> Bool
not Bool
xSigned, Bool
ySigned, Just Int
xW <- Maybe Int
xWidth, Just Int
yW <- Maybe Int
yWidth = Int
xW Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<  Int
yW

  | Bool
otherwise = Bool
False
  where
    xWidth :: Maybe Int
xWidth  = a -> Maybe Int
forall a. Bits a => a -> Maybe Int
bitSizeMaybe a
x
    xSigned :: Bool
xSigned = a -> Bool
forall a. Bits a => a -> Bool
isSigned     a
x

    yWidth :: Maybe Int
yWidth  = b -> Maybe Int
forall a. Bits a => a -> Maybe Int
bitSizeMaybe b
y
    ySigned :: Bool
ySigned = b -> Bool
forall a. Bits a => a -> Bool
isSigned     b
y
{-# INLINE isBitSubType #-}

{-
Note [Constant folding for rotate]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The INLINE on the Int instance of rotate enables it to be constant
folded.  For example:
     sumU . mapU (`rotate` 3) . replicateU 10000000 $ (7 :: Int)
goes to:
   Main.$wfold =
     \ (ww_sO7 :: Int#) (ww1_sOb :: Int#) ->
       case ww1_sOb of wild_XM {
         __DEFAULT -> Main.$wfold (+# ww_sO7 56) (+# wild_XM 1);
         10000000 -> ww_sO7
whereas before it was left as a call to $wrotate.

All other Bits instances seem to inline well enough on their
own to enable constant folding; for example 'shift':
     sumU . mapU (`shift` 3) . replicateU 10000000 $ (7 :: Int)
 goes to:
     Main.$wfold =
       \ (ww_sOb :: Int#) (ww1_sOf :: Int#) ->
         case ww1_sOf of wild_XM {
           __DEFAULT -> Main.$wfold (+# ww_sOb 56) (+# wild_XM 1);
           10000000 -> ww_sOb
         }
-}

-- Note [toIntegralSized optimization]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- The code in 'toIntegralSized' relies on GHC optimizing away statically
-- decidable branches.
--
-- If both integral types are statically known, GHC will be able optimize the
-- code significantly (for @-O1@ and better).
--
-- For instance (as of GHC 7.8.1) the following definitions:
--
-- > w16_to_i32 = toIntegralSized :: Word16 -> Maybe Int32
-- >
-- > i16_to_w16 = toIntegralSized :: Int16 -> Maybe Word16
--
-- are translated into the following (simplified) /GHC Core/ language:
--
-- > w16_to_i32 = \x -> Just (case x of _ { W16# x# -> I32# (word2Int# x#) })
-- >
-- > i16_to_w16 = \x -> case eta of _
-- >   { I16# b1 -> case tagToEnum# (<=# 0 b1) of _
-- >       { False -> Nothing
-- >       ; True -> Just (W16# (narrow16Word# (int2Word# b1)))
-- >       }
-- >   }