1-- |
2-- Module      : Data.Memory.Internal.Compat
3-- License     : BSD-style
4-- Maintainer  : Vincent Hanquez <vincent@snarc.org>
5-- Stability   : stable
6-- Portability : Good
7--
8-- This module try to keep all the difference between versions of base
9-- or other needed packages, so that modules don't need to use CPP
10--
11{-# LANGUAGE CPP #-}
12module Data.Memory.Internal.Compat
13    ( unsafeDoIO
14    , popCount
15    , unsafeShiftL
16    , unsafeShiftR
17    , byteSwap64
18    , byteSwap32
19    , byteSwap16
20    ) where
21
22import System.IO.Unsafe
23import Data.Word
24import Data.Bits
25
26-- | perform io for hashes that do allocation and ffi.
27-- unsafeDupablePerformIO is used when possible as the
28-- computation is pure and the output is directly linked
29-- to the input. we also do not modify anything after it has
30-- been returned to the user.
31unsafeDoIO :: IO a -> a
32#if __GLASGOW_HASKELL__ > 704
33unsafeDoIO = unsafeDupablePerformIO
34#else
35unsafeDoIO = unsafePerformIO
36#endif
37
38#if !(MIN_VERSION_base(4,5,0))
39popCount :: Word64 -> Int
40popCount n = loop 0 n
41  where loop c 0 = c
42        loop c i = loop (c + if testBit c 0 then 1 else 0) (i `shiftR` 1)
43#endif
44
45#if !(MIN_VERSION_base(4,7,0))
46byteSwap64 :: Word64 -> Word64
47byteSwap64 w =
48        (w `shiftR` 56)                  .|. (w `shiftL` 56)
49    .|. ((w `shiftR` 40) .&. 0xff00)     .|. ((w .&. 0xff00) `shiftL` 40)
50    .|. ((w `shiftR` 24) .&. 0xff0000)   .|. ((w .&. 0xff0000) `shiftL` 24)
51    .|. ((w `shiftR` 8)  .&. 0xff000000) .|. ((w .&. 0xff000000) `shiftL` 8)
52#endif
53
54#if !(MIN_VERSION_base(4,7,0))
55byteSwap32 :: Word32 -> Word32
56byteSwap32 w =
57        (w `shiftR` 24)
58    .|. (w `shiftL` 24)
59    .|. ((w `shiftR` 8) .&. 0xff00)
60    .|. ((w .&. 0xff00) `shiftL` 8)
61#endif
62
63#if !(MIN_VERSION_base(4,7,0))
64byteSwap16 :: Word16 -> Word16
65byteSwap16 w =
66    (w `shiftR` 8) .|. (w `shiftL` 8)
67#endif
68
69#if !(MIN_VERSION_base(4,5,0))
70unsafeShiftL :: Bits a => a -> Int -> a
71unsafeShiftL = shiftL
72
73unsafeShiftR :: Bits a => a -> Int -> a
74unsafeShiftR = shiftR
75#endif
76
77