module Data.Primitive.MutVar (
MutVar(..),
newMutVar,
readMutVar,
writeMutVar,
atomicModifyMutVar,
modifyMutVar
) where
import Control.Monad.Primitive ( PrimMonad(..), primitive_ )
import GHC.Prim ( MutVar#, sameMutVar#, newMutVar#,
readMutVar#, writeMutVar#, atomicModifyMutVar# )
import Data.Typeable ( Typeable )
data MutVar s a = MutVar (MutVar# s a)
deriving ( Typeable )
instance Eq (MutVar s a) where
MutVar mva# == MutVar mvb# = sameMutVar# mva# mvb#
newMutVar :: PrimMonad m => a -> m (MutVar (PrimState m) a)
newMutVar initialValue = primitive $ \s# ->
case newMutVar# initialValue s# of
(# s'#, mv# #) -> (# s'#, MutVar mv# #)
readMutVar :: PrimMonad m => MutVar (PrimState m) a -> m a
readMutVar (MutVar mv#) = primitive (readMutVar# mv#)
writeMutVar :: PrimMonad m => MutVar (PrimState m) a -> a -> m ()
writeMutVar (MutVar mv#) newValue = primitive_ (writeMutVar# mv# newValue)
atomicModifyMutVar :: PrimMonad m => MutVar (PrimState m) a -> (a -> (a,b)) -> m b
atomicModifyMutVar (MutVar mv#) f = primitive $ atomicModifyMutVar# mv# f
modifyMutVar :: PrimMonad m => MutVar (PrimState m) a -> (a -> a) -> m ()
modifyMutVar (MutVar mv#) g = primitive_ $ \s# ->
case readMutVar# mv# s# of
(# s'#, a #) -> writeMutVar# mv# (g a) s'#