Add Data.Primitive.MutVar, bump version to 0.4.1
[darcs-mirrors/primitive.git] / Data / Primitive / MutVar.hs
1 {-# LANGUAGE MagicHash, UnboxedTuples, DeriveDataTypeable #-}
2
3 -- |
4 -- Module : Data.Primitive.MutVar
5 -- Copyright : (c) Justin Bonnar 2011
6 -- License : BSD-style
7 --
8 -- Maintainer : Justin Bonnar <justinbonnar@gmail.com>
9 -- Portability : non-portable
10 --
11 -- Primitive boxed mutable variables
12 --
13
14 module Data.Primitive.MutVar (
15 MutVar(..),
16
17 newMutVar,
18 readMutVar,
19 writeMutVar,
20
21 modifyMutVar
22 ) where
23
24 import Control.Monad.Primitive ( PrimMonad(..), primitive_ )
25 import GHC.Prim ( MutVar#, sameMutVar#, newMutVar#, readMutVar#, writeMutVar# )
26 import Data.Typeable ( Typeable )
27
28 -- | A 'MutVar' behaves like a single-element mutable array associated
29 -- with a primitive state token.
30 data MutVar s a = MutVar (MutVar# s a)
31 deriving ( Typeable )
32
33 instance Eq (MutVar s a) where
34 MutVar mva# == MutVar mvb# = sameMutVar# mva# mvb#
35
36 -- | Create a new 'MutVar' with the specified initial value
37 newMutVar :: PrimMonad m => a -> m (MutVar (PrimState m) a)
38 {-# INLINE newMutVar #-}
39 newMutVar initialValue = primitive $ \s# ->
40 case newMutVar# initialValue s# of
41 (# s'#, mv# #) -> (# s'#, MutVar mv# #)
42
43 -- | Read the value of a 'MutVar'
44 readMutVar :: PrimMonad m => MutVar (PrimState m) a -> m a
45 {-# INLINE readMutVar #-}
46 readMutVar (MutVar mv#) = primitive (readMutVar# mv#)
47
48 -- | Write a new value into a 'MutVar'
49 writeMutVar :: PrimMonad m => MutVar (PrimState m) a -> a -> m ()
50 {-# INLINE writeMutVar #-}
51 writeMutVar (MutVar mv#) newValue = primitive_ (writeMutVar# mv# newValue)
52
53 -- | Mutate the contents of a 'MutVar'
54 modifyMutVar :: PrimMonad m => MutVar (PrimState m) a -> (a -> a) -> m ()
55 {-# INLINE modifyMutVar #-}
56 modifyMutVar (MutVar mv#) g = primitive_ $ \s# ->
57 case readMutVar# mv# s# of
58 (# s'#, a #) -> writeMutVar# mv# (g a) s'#