module Data.Mutable.SRef
(
SRef
, IOSRef
, asSRef
, MutableRef (..)
) where
import Data.Mutable.Class
import Foreign.ForeignPtr
import Foreign.Storable
import Control.Monad.Primitive
newtype SRef s a = SRef (ForeignPtr a)
asSRef :: SRef s a -> SRef s a
asSRef x = x
type IOSRef = SRef (PrimState IO)
instance MutableContainer (SRef s a) where
type MCState (SRef s a) = s
instance Storable a => MutableRef (SRef s a) where
type RefElement (SRef s a) = a
newRef x = unsafePrimToPrim $ do
fptr <- mallocForeignPtr
withForeignPtr fptr $ flip poke x
return $! SRef fptr
readRef (SRef fptr) = unsafePrimToPrim $ withForeignPtr fptr peek
writeRef (SRef fptr) x = unsafePrimToPrim $ withForeignPtr fptr $ flip poke x
modifyRef (SRef fptr) f = unsafePrimToPrim $ withForeignPtr fptr $ \ptr ->
peek ptr >>= poke ptr . f
modifyRef' = modifyRef