Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve MutVar interop with IORef and STRef #423

Merged
merged 1 commit into from
Nov 18, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 30 additions & 2 deletions Data/Primitive/MutVar.hs
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,24 @@ module Data.Primitive.MutVar (
readMutVar,
writeMutVar,

-- * Modify
atomicModifyMutVar,
atomicModifyMutVar',
modifyMutVar,
modifyMutVar'
modifyMutVar',
-- * Interop with STRef and IORef
mutVarFromIORef,
mutVarToIORef,
mutVarFromSTRef,
mutVarToSTRef
) where

import Control.Monad.Primitive ( PrimMonad(..), primitive_ )
import GHC.IORef (IORef(IORef))
import GHC.STRef (STRef(STRef))
import GHC.Exts ( MutVar#, sameMutVar#, newMutVar#
, readMutVar#, writeMutVar#, atomicModifyMutVar#
, isTrue# )
, isTrue#, RealWorld)
import Data.Typeable ( Typeable )

-- | A 'MutVar' behaves like a single-element mutable array associated
Expand Down Expand Up @@ -103,3 +111,23 @@ modifyMutVar' :: PrimMonad m => MutVar (PrimState m) a -> (a -> a) -> m ()
modifyMutVar' (MutVar mv#) g = primitive_ $ \s# ->
case readMutVar# mv# s# of
(# s'#, a #) -> let a' = g a in a' `seq` writeMutVar# mv# a' s'#

-- | Convert 'MutVar' to 'IORef'
mutVarToIORef :: MutVar RealWorld a -> IORef a
{-# INLINE mutVarToIORef #-}
mutVarToIORef (MutVar mv#) = IORef (STRef mv#)

-- | Convert 'MutVar' to 'IORef'
mutVarFromIORef :: IORef a -> MutVar RealWorld a
{-# INLINE mutVarFromIORef #-}
mutVarFromIORef (IORef (STRef mv#)) = MutVar mv#

-- | Convert 'MutVar' to 'STRef'
mutVarToSTRef :: MutVar s a -> STRef s a
{-# INLINE mutVarToSTRef #-}
mutVarToSTRef (MutVar mv#) = STRef mv#

-- | Convert 'MutVar' to 'STRef'
mutVarFromSTRef :: STRef s a -> MutVar s a
{-# INLINE mutVarFromSTRef #-}
mutVarFromSTRef (STRef mv#) = MutVar mv#
Loading