{-# LANGUAGE MagicHash #-}
{-# LANGUAGE TypeFamilies #-}
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
{-# INLINE asPRef #-}
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
{-# INLINE newRef #-}
readRef (PRef ba) = readByteArray ba 0
{-# INLINE readRef #-}
writeRef (PRef ba) = writeByteArray ba 0
{-# INLINE writeRef #-}
modifyRef (PRef ba) f = do
x <- readByteArray ba 0
writeByteArray ba 0 $! f x
{-# INLINE modifyRef #-}
modifyRef' = modifyRef
{-# INLINE modifyRef' #-}