583610ff4bbcac583e00041ccafbb4cf8b672ade
[ghc-hetmet.git] / ghc / lib / std / PrelMarshalError.lhs
1 % -----------------------------------------------------------------------------
2 % $Id: PrelMarshalError.lhs,v 1.2 2001/05/18 16:54:05 simonmar Exp $
3 %
4 % (c) The FFI task force, 2000
5 %
6
7 Marshalling support: Handling of common error conditions
8
9 \begin{code}
10 {-# OPTIONS -fno-implicit-prelude #-}
11
12 module PrelMarshalError (
13
14   -- throw an exception on specific return values
15   --
16   throwIf,       -- :: (a -> Bool) -> (a -> String) -> IO a       -> IO a
17   throwIf_,      -- :: (a -> Bool) -> (a -> String) -> IO a       -> IO ()
18   throwIfNeg,    -- :: (Ord a, Num a) 
19                  -- =>                (a -> String) -> IO a       -> IO a
20   throwIfNeg_,   -- :: (Ord a, Num a)
21                  -- =>                (a -> String) -> IO a       -> IO ()
22   throwIfNull,   -- ::                String        -> IO (Ptr a) -> IO (Ptr a)
23
24   -- discard return value
25   --
26   void           -- IO a -> IO ()
27 ) where
28
29 import PrelPtr
30 import PrelIOBase
31 import PrelNum
32 import PrelBase
33
34 -- exported functions
35 -- ------------------
36
37 -- guard an IO operation and throw an exception if the result meets the given
38 -- predicate 
39 --
40 -- * the second argument computes an error message from the result of the IO
41 --   operation
42 --
43 throwIf                 :: (a -> Bool) -> (a -> String) -> IO a -> IO a
44 throwIf pred msgfct act  = 
45   do
46     res <- act
47     (if pred res then ioError . userError . msgfct else return) res
48
49 -- like `throwIf', but discarding the result
50 --
51 throwIf_                 :: (a -> Bool) -> (a -> String) -> IO a -> IO ()
52 throwIf_ pred msgfct act  = void $ throwIf pred msgfct act
53
54 -- guards against negative result values
55 --
56 throwIfNeg :: (Ord a, Num a) => (a -> String) -> IO a -> IO a
57 throwIfNeg  = throwIf (< 0)
58
59 -- like `throwIfNeg', but discarding the result
60 --
61 throwIfNeg_ :: (Ord a, Num a) => (a -> String) -> IO a -> IO ()
62 throwIfNeg_  = throwIf_ (< 0)
63
64 -- guards against null pointers
65 --
66 throwIfNull :: String -> IO (Ptr a) -> IO (Ptr a)
67 throwIfNull  = throwIf (== nullPtr) . const
68
69 -- discard the return value of an IO action
70 --
71 void     :: IO a -> IO ()
72 void act  = act >> return ()
73
74 \end{code}