1{-# LANGUAGE UnboxedTuples #-}
4-- Module : Streamly.Internal.Data.IORef.Prim
5-- Copyright : (c) 2019 Composewell Technologies
8-- Maintainer : streamly@composewell.com
9-- Stability : experimental
12-- A mutable variable in a mutation capable monad (IO) holding a 'Prim'
13-- value. This allows fast modification because of unboxed storage.
15-- = Multithread Consistency Notes
17-- In general, any value that straddles a machine word cannot be guaranteed to
18-- be consistently read from another thread without a lock. GHC heap objects
19-- are always machine word aligned, therefore, a 'IORef' is also word aligned.
20-- On a 64-bit platform, writing a 64-bit aligned type from one thread and
21-- reading it from another thread should give consistent old or new value. The
22-- same holds true for 32-bit values on a 32-bit platform.
24module Streamly.Internal.Data.IORef.Prim
44import Control.Monad.IO.Class (MonadIO(..))
45import Control.Monad.Primitive (primitive_)
46import Data.Primitive.Types (Prim, sizeOf#, readByteArray#, writeByteArray#)
47import GHC.Exts (MutableByteArray#, newByteArray#, RealWorld)
50import qualified Streamly.Internal.Data.Stream.StreamD.Type as D
52-- | An 'IORef' holds a single 'Prim' value.
53data IORef a = IORef (MutableByteArray# RealWorld)
55-- | Create a new 'IORef'.
58{-# INLINE newIORef #-}
59newIORef :: forall a. Prim a => a -> IO (IORef a)
60newIORef x = IO (\s# ->
61 case newByteArray# (sizeOf# (undefined :: a)) s# of
63 case writeByteArray# arr# 0# x s1# of
64 s2# -> (# s2#, IORef arr# #)
67-- | Write a value to an 'IORef'.
70{-# INLINE writeIORef #-}
71writeIORef :: Prim a => IORef a -> a -> IO ()
72writeIORef (IORef arr#) x = primitive_ (writeByteArray# arr# 0# x)
74-- | Read a value from an 'IORef'.
77{-# INLINE readIORef #-}
78readIORef :: Prim a => IORef a -> IO a
79readIORef (IORef arr#) = IO (readByteArray# arr# 0#)
81-- | Modify the value of an 'IORef' using a function with strict application.
84{-# INLINE modifyIORef' #-}
85modifyIORef' :: Prim a => IORef a -> (a -> a) -> IO ()
86modifyIORef' (IORef arr#) g = primitive_ $ \s# ->
87 case readByteArray# arr# 0# s# of
88 (# s'#, a #) -> let a' = g a in a' `seq` writeByteArray# arr# 0# a' s'#
90-- | Generate a stream by continuously reading the IORef.
93{-# INLINE_NORMAL toStreamD #-}
94toStreamD :: (MonadIO m, Prim a) => IORef a -> D.Stream m a
95toStreamD var = D.Stream step ()
99 {-# INLINE_LATE step #-}
100 step _ () = liftIO (readIORef var) >>= \x -> return $ D.Yield x ()
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list