module Data.Mutable.PRef
(
PRef
, IOPRef
, asPRef
, MutableRef (..)
) where
import Data.Mutable.Class
import Data.Primitive (sizeOf)
import Data.Primitive.ByteArray (MutableByteArray, newByteArray, readByteArray,
writeByteArray)
import Data.Primitive.Types (Prim)
newtype PRef s a = PRef (MutableByteArray s)
asPRef :: PRef s a -> PRef s a
asPRef x = x
type IOPRef = PRef (PrimState IO)
instance MutableContainer (PRef s a) where
type MCState (PRef s a) = s
instance Prim a => MutableRef (PRef s a) where
type RefElement (PRef s a) = a
newRef x = do
ba <- newByteArray (sizeOf $! x)
writeByteArray ba 0 x
return $! PRef ba
readRef (PRef ba) = readByteArray ba 0
writeRef (PRef ba) = writeByteArray ba 0
modifyRef (PRef ba) f = do
x <- readByteArray ba 0
writeByteArray ba 0 $! f x
modifyRef' = modifyRef