{-# LANGUAGE BangPatterns, MagicHash, UnboxedTuples #-}
{-# OPTIONS_GHC -O2 #-}
-- We always optimise this, otherwise performance of a non-optimised
-- compiler is severely affected
--
-- (c) The University of Glasgow 2002-2006
--
-- Unboxed mutable Ints

module GHC.Data.FastMutInt(
        FastMutInt, newFastMutInt,
        readFastMutInt, writeFastMutInt,
        atomicFetchAddFastMut
  ) where

import GHC.Prelude

import GHC.Base

data FastMutInt = FastMutInt !(MutableByteArray# RealWorld)

newFastMutInt :: Int -> IO FastMutInt
newFastMutInt :: Int -> IO FastMutInt
newFastMutInt Int
n = do
    FastMutInt
x <- IO FastMutInt
create
    FastMutInt -> Int -> IO ()
writeFastMutInt FastMutInt
x Int
n
    forall (m :: * -> *) a. Monad m => a -> m a
return FastMutInt
x
  where
    !(I# Int#
size) = forall b. FiniteBits b => b -> Int
finiteBitSize (Int
0 :: Int) forall a. Bits a => a -> Int -> a
`unsafeShiftR` Int
3
    create :: IO FastMutInt
create = forall a. (State# RealWorld -> (# State# RealWorld, a #)) -> IO a
IO forall a b. (a -> b) -> a -> b
$ \State# RealWorld
s ->
      case forall d. Int# -> State# d -> (# State# d, MutableByteArray# d #)
newByteArray# Int#
size State# RealWorld
s of
        (# State# RealWorld
s, MutableByteArray# RealWorld
arr #) -> (# State# RealWorld
s, MutableByteArray# RealWorld -> FastMutInt
FastMutInt MutableByteArray# RealWorld
arr #)

readFastMutInt :: FastMutInt -> IO Int
readFastMutInt :: FastMutInt -> IO Int
readFastMutInt (FastMutInt MutableByteArray# RealWorld
arr) = forall a. (State# RealWorld -> (# State# RealWorld, a #)) -> IO a
IO forall a b. (a -> b) -> a -> b
$ \State# RealWorld
s ->
  case forall d.
MutableByteArray# d -> Int# -> State# d -> (# State# d, Int# #)
readIntArray# MutableByteArray# RealWorld
arr Int#
0# State# RealWorld
s of
    (# State# RealWorld
s, Int#
i #) -> (# State# RealWorld
s, Int# -> Int
I# Int#
i #)

writeFastMutInt :: FastMutInt -> Int -> IO ()
writeFastMutInt :: FastMutInt -> Int -> IO ()
writeFastMutInt (FastMutInt MutableByteArray# RealWorld
arr) (I# Int#
i) = forall a. (State# RealWorld -> (# State# RealWorld, a #)) -> IO a
IO forall a b. (a -> b) -> a -> b
$ \State# RealWorld
s ->
  case forall d.
MutableByteArray# d -> Int# -> Int# -> State# d -> State# d
writeIntArray# MutableByteArray# RealWorld
arr Int#
0# Int#
i State# RealWorld
s of
    State# RealWorld
s -> (# State# RealWorld
s, () #)

atomicFetchAddFastMut :: FastMutInt -> Int -> IO Int
atomicFetchAddFastMut :: FastMutInt -> Int -> IO Int
atomicFetchAddFastMut (FastMutInt MutableByteArray# RealWorld
arr) (I# Int#
i) = forall a. (State# RealWorld -> (# State# RealWorld, a #)) -> IO a
IO forall a b. (a -> b) -> a -> b
$ \State# RealWorld
s ->
  case forall d.
MutableByteArray# d
-> Int# -> Int# -> State# d -> (# State# d, Int# #)
fetchAddIntArray# MutableByteArray# RealWorld
arr Int#
0# Int#
i State# RealWorld
s of
    (# State# RealWorld
s, Int#
n #) -> (# State# RealWorld
s, Int# -> Int
I# Int#
n #)