[project @ 1998-12-02 13:17:09 by simonm]
[ghc-hetmet.git] / ghc / lib / std / PrelWeak.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1998
3 %
4
5 \section[PrelWeak]{Module @PrelWeak@}
6
7 \begin{code}
8 {-# OPTIONS -fno-implicit-prelude #-}
9
10 module PrelWeak where
11
12 import PrelGHC
13 import PrelMaybe
14 import PrelBase
15 import PrelIOBase
16 import PrelForeign
17
18 data Weak v = Weak (Weak# v)
19
20 mkWeak  :: k                            -- key
21         -> v                            -- value
22         -> IO ()                        -- finaliser
23         -> IO (Weak v)                  -- weak pointer
24
25 mkWeak key val finaliser = IO $ \s ->
26    case mkWeak# key val finaliser s of { (# s, w #) ->
27    (# s, Weak w #) }
28
29 deRefWeak :: Weak v -> IO (Maybe v)
30 deRefWeak (Weak w) = IO $ \s ->
31    case deRefWeak# w s of
32         (# s, flag, w #) -> case flag of
33                                 0# -> (# s, Nothing #)
34                                 _  -> (# s, Just w #)
35
36 mkWeakPtr :: k -> IO () -> IO (Weak k)
37 mkWeakPtr key finaliser = mkWeak key key finaliser
38
39 mkWeakPair :: k -> v -> IO () -> IO (Weak (k,v))
40 mkWeakPair key val finaliser = mkWeak key (key,val) finaliser
41
42 addFinaliser :: key -> IO () -> IO ()
43 addFinaliser key finaliser = do
44    mkWeakPtr key finaliser              -- throw it away
45    return ()
46
47 addForeignFinaliser :: ForeignObj -> IO () -> IO ()
48 addForeignFinaliser (ForeignObj fo) finaliser = addFinaliser fo finaliser
49
50 {-
51 finalise :: Weak v -> IO ()
52 finalise (Weak w) = finaliseWeak# w
53
54 instance Eq (Weak v) where
55   (Weak w1) == (Weak w2) = w1 `sameWeak#` w2
56 -}
57
58 \end{code}