4d75b31446f6d00ab375508db7d11bc8971b83e8
[ghc-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 -- Weak references, weak pairs, weak pointers, and finalizers.
12 --
13 -----------------------------------------------------------------------------
14
15 module System.Mem.Weak (
16         Weak,                   -- abstract
17         -- instance Eq (Weak v)  
18
19         mkWeak,                 -- :: k -> v -> Maybe (IO ()) -> IO (Weak v)
20         deRefWeak,              -- :: Weak v -> IO (Maybe v)
21         finalize,               -- :: Weak v -> IO ()
22         -- replaceFinaliser     -- :: Weak v -> IO () -> IO ()
23
24         mkWeakPtr,              -- :: k -> Maybe (IO ()) -> IO (Weak k)
25         mkWeakPair,             -- :: k -> v -> Maybe (IO ()) -> IO (Weak (k,v))
26         addFinalizer            -- :: key -> IO () -> IO ()
27    ) where
28
29 import Prelude
30
31 import Data.Dynamic
32
33 #ifdef __GLASGOW_HASKELL__
34 import GHC.Base
35 import GHC.IOBase
36 import GHC.Weak
37
38 #include "Dynamic.h"
39 INSTANCE_TYPEABLE1(Weak,weakTc,"Weak")
40
41 deRefWeak :: Weak v -> IO (Maybe v)
42 deRefWeak (Weak w) = IO $ \s ->
43    case deRefWeak# w s of
44         (# s1, flag, p #) -> case flag of
45                                 0# -> (# s1, Nothing #)
46                                 _  -> (# s1, Just p #)
47
48 mkWeakPair :: k -> v -> Maybe (IO ()) -> IO (Weak (k,v))
49 mkWeakPair key val finalizer = mkWeak key (key,val) finalizer
50
51 finalize :: Weak v -> IO ()
52 finalize (Weak w) = IO $ \s ->
53    case finalizeWeak# w s of 
54         (# s1, 0#, _ #) -> (# s1, () #) -- already dead, or no finaliser
55         (# s1, _,  f #) -> f s1
56 #endif
57