[project @ 2001-06-28 14:15:04 by simonmar]
[packages/old-locale.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.1 2001/06/28 14:15:04 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 #include "Dynamic.h"
34 INSTANCE_TYPEABLE0(Weak,weakTc,"Weak")
35
36 #ifdef __GLASGOW_HASKELL__
37 import GHC.Base
38 import GHC.IOBase
39 import GHC.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