on develop help sign in
reflex/src/Data/FastWeakBag.hs
161 lines 6.9 kB history raw
1{-# LANGUAGE CPP #-}
2{-# LANGUAGE ExistentialQuantification #-}
3#ifdef USE_REFLEX_OPTIMIZER
4{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
5#endif
6#ifdef GHCJS_FAST_WEAK
7{-# LANGUAGE ForeignFunctionInterface #-}
8{-# LANGUAGE JavaScriptFFI #-}
9#endif
10-- | This module defines the 'FastWeakBag' type, which represents a mutable
11-- collection of items that does not cause the items to be retained in memory.
12-- This is useful for situations where a value needs to be inspected or modified
13-- if it is still alive, but can be ignored if it is dead.
14module Data.FastWeakBag
15 ( FastWeakBag
16 , FastWeakBagTicket
17 , empty
18 , isEmpty
19 , insert
20 , traverse
21 , traverse_
22 , remove
23 -- * Internal functions
24 -- These will not always be available.
25#ifndef GHCJS_FAST_WEAK
26 , _weakBag_children --TODO: Don't export this
27#endif
28 ) where
30import Prelude hiding (traverse)
32import Control.Monad
33import Control.Monad.IO.Class
35#ifdef GHCJS_FAST_WEAK
36import GHCJS.Types
37import Reflex.FastWeak (js_isNull, unsafeFromRawJSVal, unsafeToRawJSVal)
38#else
39import Control.Exception
40import Data.IntMap.Strict (IntMap)
41import qualified Data.IntMap.Strict as IntMap
42import Data.IORef
43import System.Mem.Weak
44#endif
46-- | A 'FastWeakBag' holds a set of values of type @/a/@, but does not retain them -
47-- that is, they can still be garbage-collected. As long as the @/a/@ values remain
48-- alive, the 'FastWeakBag' will continue to refer to them.
49#ifdef GHCJS_FAST_WEAK
50newtype FastWeakBag a = FastWeakBag JSVal
51#else
52data FastWeakBag a = FastWeakBag
53 { _weakBag_nextId :: {-# UNPACK #-} !(IORef Int) --TODO: what if this wraps around?
54 , _weakBag_children :: {-# UNPACK #-} !(IORef (IntMap (Weak a))) -- ^ Map of items contained by the 'FastWeakBag'
55 }
56#endif
58-- | When inserting an item into a 'FastWeakBag', a 'FastWeakBagTicket' is returned. If
59-- the caller retains the ticket, the item is guranteed to stay in memory (and
60-- thus in the 'FastWeakBag'). The ticket can also be used to remove the item from
61-- the 'FastWeakBag' prematurely (i.e. while it is still alive), using 'remove'.
62#ifdef GHCJS_FAST_WEAK
63newtype FastWeakBagTicket a = FastWeakBagTicket JSVal
64#else
65data FastWeakBagTicket a = FastWeakBagTicket
66 { _weakBagTicket_weakItem :: {-# UNPACK #-} !(Weak a)
67 , _weakBagTicket_item :: {-# NOUNPACK #-} !a
68 }
69#endif
71-- | Insert an item into a 'FastWeakBag'.
72{-# INLINE insert #-}
73insert :: a -- ^ The item
74 -> FastWeakBag a -- ^ The 'FastWeakBag' to insert into
75 -> IO (FastWeakBagTicket a) -- ^ Returns a 'FastWeakBagTicket' that ensures the item
76 -- is retained and allows the item to be removed.
77#ifdef GHCJS_FAST_WEAK
78insert a wb = js_insert (unsafeToRawJSVal a) wb
79foreign import javascript unsafe "$r = new h$FastWeakBagTicket($2, $1);" js_insert :: JSVal -> FastWeakBag a -> IO (FastWeakBagTicket a)
80#else
81insert a (FastWeakBag nextId children) = {-# SCC "insert" #-} do
82 a' <- evaluate a
83 myId <- atomicModifyIORef' nextId $ \n -> (succ n, n)
84 let cleanup = atomicModifyIORef' children $ \cs -> (IntMap.delete myId cs, ())
85 wa <- mkWeakPtr a' $ Just cleanup
86 atomicModifyIORef' children $ \cs -> (IntMap.insert myId wa cs, ())
87 return $ FastWeakBagTicket
88 { _weakBagTicket_weakItem = wa
89 , _weakBagTicket_item = a'
90 }
91#endif
93-- | Create an empty 'FastWeakBag'.
94{-# INLINE empty #-}
95empty :: IO (FastWeakBag a)
96#ifdef GHCJS_FAST_WEAK
97empty = js_empty
98foreign import javascript unsafe "$r = new h$FastWeakBag();" js_empty :: IO (FastWeakBag a)
99#else
100empty = {-# SCC "empty" #-} do
101 nextId <- newIORef 1
102 children <- newIORef IntMap.empty
103 let bag = FastWeakBag
104 { _weakBag_nextId = nextId
105 , _weakBag_children = children
106 }
107 return bag
108#endif
110-- | Check whether a 'FastWeakBag' is empty.
111{-# INLINE isEmpty #-}
112isEmpty :: FastWeakBag a -> IO Bool
113#ifdef GHCJS_FAST_WEAK
114isEmpty = js_isEmpty
115foreign import javascript unsafe "(function(){ for(var i = 0; i < $1.tickets.length; i++) { if($1.tickets[i] !== null) { return false; } }; return true; })()" js_isEmpty :: FastWeakBag a -> IO Bool --TODO: Clean up as we go along so this isn't O(n) every time
116#else
117isEmpty bag = {-# SCC "isEmpty" #-} IntMap.null <$> readIORef (_weakBag_children bag)
118#endif
120{-# INLINE traverse_ #-}
121-- | Visit every node in the given list. If new nodes are appended during the
122-- traversal, they will not be visited. Every live node that was in the list
123-- when the traversal began will be visited exactly once; however, no guarantee
124-- is made about the order of the traversal.
125traverse_ :: forall a m. MonadIO m => FastWeakBag a -> (a -> m ()) -> m ()
126#ifdef GHCJS_FAST_WEAK
127traverse_ wb f = do
128 let go cursor = when (not $ js_isNull cursor) $ do
129 val <- liftIO $ js_getTicketValue cursor
130 f $ unsafeFromRawJSVal val
131 go =<< liftIO (js_getNext (FastWeakBagTicket cursor))
132 go =<< liftIO (js_getInitial wb)
133foreign import javascript unsafe "(function(){ for(var i = $1.tickets.length - 1; i >= 0; i--) { if($1.tickets[i] !== null) { return $1.tickets[i]; } }; return null; })()" js_getInitial :: FastWeakBag a -> IO JSVal --TODO: Clean up as we go along so this isn't O(n) every time -- Result can be null or a FastWeakBagTicket a
134foreign import javascript unsafe "$r = $1.val;" js_getTicketValue :: JSVal -> IO JSVal
135--TODO: Fix the race condition where if a cursor is deleted (presumably using 'remove', below) while we're holding it, it can't find its way back to the correct bag
136foreign import javascript unsafe "(function(){ for(var i = $1.pos - 1; i >= 0; i--) { if($1.bag.tickets[i] !== null) { return $1.bag.tickets[i]; } }; return null; })()" js_getNext :: FastWeakBagTicket a -> IO JSVal --TODO: Clean up as we go along so this isn't O(n) every time -- Result can be null or a FastWeakBagTicket a
137#else
138traverse_ (FastWeakBag _ children) f = {-# SCC "traverse_" #-} do
139 cs <- liftIO $ readIORef children
140 forM_ cs $ \c -> do
141 ma <- liftIO $ deRefWeak c
142 mapM_ f ma
143#endif
145{-# DEPRECATED traverse "Use 'traverse_' instead" #-}
146traverse :: forall a m. MonadIO m => FastWeakBag a -> (a -> m ()) -> m ()
147traverse = traverse_
149-- | Remove an item from the 'FastWeakBag'; does nothing if invoked multiple times
150-- on the same 'FastWeakBagTicket'.
151{-# INLINE remove #-}
152remove :: FastWeakBagTicket a -> IO ()
153#ifdef GHCJS_FAST_WEAK
154remove = js_remove
155foreign import javascript unsafe "$1.bag.tickets[$1.pos] = null; $1.bag = new h$FastWeakBag(); $1.bag.tickets.push($1); $1.pos = 0;" js_remove :: FastWeakBagTicket a -> IO () --TODO: Don't bother with the new surrogate FastWeakBag; instead, make the GC check for bag === null, and then null it out here
156#else
157remove (FastWeakBagTicket w _) = {-# SCC "remove" #-} finalize w
158#endif
159--TODO: Should 'remove' also drop the reference to the item?
161--TODO: can/should we provide a null FastWeakBagTicket?