module Data.PrimRef (
PrimRef
, newPrimRef
, readPrimRef
, writePrimRef
, modifyPrimRef
, modifyPrimRef'
) where
import Control.Monad.Primitive (PrimMonad(..))
import GHC.Base (MutVar#,newMutVar#,readMutVar#,writeMutVar#)
import Prelude (($),($!))
data PrimRef m a = PrimRef (MutVar# (PrimState m) a)
newPrimRef :: PrimMonad m => a -> m (PrimRef m a)
newPrimRef a = primitive $ \s1# ->
case newMutVar# a s1# of
(# s2#, var# #) -> (# s2#, PrimRef var# #)
readPrimRef :: PrimMonad m => PrimRef m a -> m a
readPrimRef (PrimRef var#)
= primitive $ \s1# -> readMutVar# var# s1#
writePrimRef :: PrimMonad m => PrimRef m a -> a -> m ()
writePrimRef (PrimRef var#) a
= primitive $ \s1# ->
case writeMutVar# var# a s1# of
s2# -> (# s2#, () #)
modifyPrimRef :: PrimMonad m => PrimRef m a -> (a -> a) -> m ()
modifyPrimRef var f = do
x <- readPrimRef var
writePrimRef var $ f x
modifyPrimRef' :: PrimMonad m => PrimRef m a -> (a -> a) -> m ()
modifyPrimRef' var f = do
x <- readPrimRef var
writePrimRef var $! f x