module Data.Primitive.MutVar (
MutVar(..),
newMutVar,
readMutVar,
writeMutVar,
modifyMutVar
) where
import Control.Monad.Primitive ( PrimMonad(..), primitive_ )
import GHC.Prim ( MutVar#, sameMutVar#, newMutVar#, readMutVar#, writeMutVar# )
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)
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'#