1 % ------------------------------------------------------------------------------
2 % $Id: PrelWeak.lhs,v 1.13 2000/06/30 13:39:36 simonmar Exp $
4 % (c) The University of Glasgow, 1998-2000
7 \section[PrelWeak]{Module @PrelWeak@}
10 {-# OPTIONS -fno-implicit-prelude #-}
17 -- NOTE: To break a cycle, ForeignObj is not in PrelForeign, but PrelIOBase!
18 import PrelIOBase ( IO(..), unIO, ForeignObj(..) )
20 #ifndef __PARALLEL_HASKELL__
22 data Weak v = Weak (Weak# v)
26 -> Maybe (IO ()) -- finalizer
27 -> IO (Weak v) -- weak pointer
29 mkWeak key val (Just finalizer) = IO $ \s ->
30 case mkWeak# key val finalizer s of { (# s1, w #) -> (# s1, Weak w #) }
31 mkWeak key val Nothing = IO $ \s ->
32 case mkWeak# key val (unsafeCoerce# 0#) s of { (# s1, w #) -> (# s1, Weak w #) }
34 mkWeakPtr :: k -> Maybe (IO ()) -> IO (Weak k)
35 mkWeakPtr key finalizer = mkWeak key key finalizer
37 addFinalizer :: key -> IO () -> IO ()
38 addFinalizer key finalizer = do
39 mkWeakPtr key (Just finalizer) -- throw it away
42 addForeignFinalizer :: ForeignObj -> IO () -> IO ()
43 addForeignFinalizer (ForeignObj fo) finalizer = addFinalizer fo finalizer
46 Instance Eq (Weak v) where
47 (Weak w1) == (Weak w2) = w1 `sameWeak#` w2
51 -- run a batch of finalizers from the garbage collector. We're given
52 -- an array of finalizers and the length of the array, and we just
53 -- call each one in turn.
55 -- the IO primitives are inlined by hand here to get the optimal
58 runFinalizerBatch :: Int -> Array# (IO ()) -> IO ()
59 runFinalizerBatch (I# n) arr =
63 _ -> let m' = m -# 1# in
64 case indexArray# arr m' of { (# io #) ->
65 case unIO io s of { (# s, _ #) ->