on master help sign in
Add a mutable variable for Prim types
97ecb28Harendra Kumar
src/Streamly/Internal/Mutable/Prim/Var.hsnew file+66
@@ -0,0 +1,66 @@
1+{-# LANGUAGE BangPatterns #-}
2+{-# LANGUAGE ConstraintKinds #-}
3+{-# LANGUAGE CPP #-}
4+{-# LANGUAGE ExistentialQuantification #-}
5+{-# LANGUAGE MagicHash #-}
6+{-# LANGUAGE RecordWildCards #-}
7+{-# LANGUAGE UnboxedTuples #-}
8+{-# LANGUAGE ScopedTypeVariables #-}
9+
10+#include "inline.hs"
11+
12+-- |
13+-- Module : Streamly.Internal.Mutable.Prim.Var
14+-- Copyright : (c) 2019 Composewell Technologies
15+--
16+-- License : BSD3
17+-- Maintainer : streamly@composewell.com
18+-- Stability : experimental
19+-- Portability : GHC
20+--
21+-- A mutable variable in a mutable monad (IO/ST) holding a 'Prim' value. This
22+-- allows fast modification of a value.
23+
24+module Streamly.Internal.Mutable.Prim.Var
25+ (
26+ Var
27+
28+ -- * Construction
29+
30+ , newVar
31+
32+ -- * modification
33+ , writeVar
34+
35+ -- * modification
36+ , readVar
37+ )
38+where
39+
40+import Control.Monad.Primitive (PrimMonad(..), primitive_)
41+import Data.Primitive.Types (Prim, sizeOf#, readByteArray#, writeByteArray#)
42+import GHC.Exts (MutableByteArray#, newByteArray#)
43+
44+-- XXX use unlifted newtype?
45+--
46+-- | A 'Var' holds a single 'Prim' value.
47+data Var m a = Var (MutableByteArray# (PrimState m))
48+
49+type MonadMut = PrimMonad
50+
51+-- | Create a new mutable variable.
52+{-# INLINE newVar #-}
53+newVar :: forall m a. (MonadMut m, Prim a) => m (Var m a)
54+newVar = primitive (\s# ->
55+ case newByteArray# (sizeOf# (undefined :: a)) s# of
56+ (# s'#, arr# #) -> (# s'#, Var arr# #)
57+ )
58+
59+-- | Write a value to a mutable variable.
60+{-# INLINE writeVar #-}
61+writeVar :: (MonadMut m, Prim a) => Var m a -> a -> m ()
62+writeVar (Var arr#) x = primitive_ (writeByteArray# arr# 0# x)
63+
64+{-# INLINE readVar #-}
65+readVar :: (MonadMut m, Prim a) => Var m a -> m a
66+readVar (Var arr#) = primitive (readByteArray# arr# 0#)
streamly.cabal+3
@@ -349,6 +349,9 @@ library
349 , Streamly.Internal.Memory.Unicode.Array
349 , Streamly.Internal.Memory.Unicode.Array
350 , Streamly.Internal.Prelude
350 , Streamly.Internal.Prelude
351
351
352+ -- Mutable data
353+ , Streamly.Internal.Mutable.Prim.Var
354+
352 if !impl(ghcjs)
355 if !impl(ghcjs)
353 exposed-modules:
356 exposed-modules:
354 Streamly.Network.Socket
357 Streamly.Network.Socket