6a092e0347e873d56d7174377d1dd4b758714f6c
[packages/base.git] / System / Mem / Weak.hs
1 -----------------------------------------------------------------------------
2 --
3 -- Module : System.Mem.Weak
4 -- Copyright : (c) The University of Glasgow 2001
5 -- License : BSD-style (see the file libraries/core/LICENSE)
6 --
7 -- Maintainer : libraries@haskell.org
8 -- Stability : experimental
9 -- Portability : non-portable
10 --
11 -- $Id: Weak.hs,v 1.2 2001/09/13 11:36:52 simonmar Exp $
12 --
13 -- Weak references, weak pairs, weak pointers, and finalizers.
14 --
15 -----------------------------------------------------------------------------
16
17 module System.Mem.Weak (
18 Weak, -- abstract
19 -- instance Eq (Weak v)
20
21 mkWeak, -- :: k -> v -> Maybe (IO ()) -> IO (Weak v)
22 deRefWeak, -- :: Weak v -> IO (Maybe v)
23 finalize, -- :: Weak v -> IO ()
24 -- replaceFinaliser -- :: Weak v -> IO () -> IO ()
25
26 mkWeakPtr, -- :: k -> Maybe (IO ()) -> IO (Weak k)
27 mkWeakPair, -- :: k -> v -> Maybe (IO ()) -> IO (Weak (k,v))
28 addFinalizer -- :: key -> IO () -> IO ()
29 ) where
30
31 import Prelude
32
33 import Data.Dynamic
34
35 #ifdef __GLASGOW_HASKELL__
36 import GHC.Base
37 import GHC.IOBase
38 import GHC.Weak
39
40 #include "Dynamic.h"
41 INSTANCE_TYPEABLE1(Weak,weakTc,"Weak")
42
43 deRefWeak :: Weak v -> IO (Maybe v)
44 deRefWeak (Weak w) = IO $ \s ->
45 case deRefWeak# w s of
46 (# s1, flag, p #) -> case flag of
47 0# -> (# s1, Nothing #)
48 _ -> (# s1, Just p #)
49
50 mkWeakPair :: k -> v -> Maybe (IO ()) -> IO (Weak (k,v))
51 mkWeakPair key val finalizer = mkWeak key (key,val) finalizer
52
53 finalize :: Weak v -> IO ()
54 finalize (Weak w) = IO $ \s ->
55 case finalizeWeak# w s of
56 (# s1, 0#, _ #) -> (# s1, () #) -- already dead, or no finaliser
57 (# s1, _, f #) -> f s1
58 #endif
59