2 % (c) The GRASP/AQUA Project, Glasgow University, 1998-2000
4 \section[Bits]{The @Bits@ interface}
6 Defines the @Bits@ class containing bit-based operations.
7 See library document for details on the semantics of the
15 import Prelude -- To generate the dependency
16 #ifdef __GLASGOW_HASKELL__
22 --ADR: The fixity for .|. conflicts with that for .|. in Fran.
23 -- Removing all fixities is a fairly safe fix; fixing the "one fixity
24 -- per symbol per program" limitation in Hugs would take a lot longer.
26 infixl 8 `shift`, `rotate`
32 class Num a => Bits a where
33 (.&.), (.|.), xor :: a -> a -> a
35 shift :: a -> Int -> a
36 rotate :: a -> Int -> a
38 setBit :: a -> Int -> a
39 clearBit :: a -> Int -> a
40 complementBit :: a -> Int -> a
41 testBit :: a -> Int -> Bool
46 x `setBit` i = x .|. bit i
47 x `clearBit` i = x .&. complement (bit i)
48 x `complementBit` i = x `xor` bit i
49 x `testBit` i = (x .&. bit i) /= 0
51 shiftL, shiftR :: Bits a => a -> Int -> a
52 rotateL, rotateR :: Bits a => a -> Int -> a
53 x `shiftL` i = x `shift` i
54 x `shiftR` i = x `shift` (-i)
55 x `rotateL` i = x `rotate` i
56 x `rotateR` i = x `rotate` (-i)
58 instance Bits Int where
59 (I# x#) .&. (I# y#) = I# (word2Int# (int2Word# x# `and#` int2Word# y#))
60 (I# x#) .|. (I# y#) = I# (word2Int# (int2Word# x# `or#` int2Word# y#))
61 (I# x#) `xor` (I# y#) = I# (word2Int# (int2Word# x# `xor#` int2Word# y#))
62 complement (I# x#) = I# (word2Int# (int2Word# x# `xor#` int2Word# (-1#)))
63 (I# x#) `shift` (I# i#)
64 | i# >=# 0# = I# (x# `iShiftL#` i#)
65 | otherwise = I# (x# `iShiftRA#` negateInt# i#)
66 (I# x#) `rotate` (I# i#) =
67 #if WORD_SIZE_IN_BYTES == 4
68 I# (word2Int# ((x'# `shiftL#` i'#) `or#`
69 (x'# `shiftRL#` (32# -# i'#))))
72 i'# = word2Int# (int2Word# i# `and#` int2Word# 31#)
74 I# (word2Int# ((x'# `shiftL#` i'#) `or#`
75 (x'# `shiftRL#` (64# -# i'#))))
78 i'# = word2Int# (int2Word# i# `and#` int2Word# 63#)
80 bitSize _ = WORD_SIZE_IN_BYTES * 8