[project @ 2002-05-09 13:16:29 by simonmar]
[packages/random.git] / Foreign / Marshal / Error.hs
1 {-# OPTIONS -fno-implicit-prelude #-}
2 -----------------------------------------------------------------------------
3 -- |
4 -- Module : Foreign.Marshal.Error
5 -- Copyright : (c) The FFI task force 2001
6 -- License : BSD-style (see the file libraries/base/LICENSE)
7 --
8 -- Maintainer : ffi@haskell.org
9 -- Stability : provisional
10 -- Portability : portable
11 --
12 -- Marshalling support: Handling of common error conditions
13 --
14 -----------------------------------------------------------------------------
15
16 module Foreign.Marshal.Error (
17 -- * Error utilities
18
19 -- |Throw an exception on specific return values
20 --
21 throwIf, -- :: (a -> Bool) -> (a -> String) -> IO a -> IO a
22 throwIf_, -- :: (a -> Bool) -> (a -> String) -> IO a -> IO ()
23 throwIfNeg, -- :: (Ord a, Num a)
24 -- => (a -> String) -> IO a -> IO a
25 throwIfNeg_, -- :: (Ord a, Num a)
26 -- => (a -> String) -> IO a -> IO ()
27 throwIfNull, -- :: String -> IO (Ptr a) -> IO (Ptr a)
28
29 -- Discard return value
30 --
31 void -- IO a -> IO ()
32 ) where
33
34 import Foreign.Ptr
35
36 #ifdef __GLASGOW_HASKELL__
37 import GHC.Base
38 import GHC.Num
39 import GHC.IOBase
40 #endif
41
42 -- exported functions
43 -- ------------------
44
45 -- |Guard an 'IO' operation and throw an exception if the result meets the given
46 -- predicate
47 --
48 -- * the second argument computes an error message from the result of the 'IO'
49 -- operation
50 --
51 throwIf :: (a -> Bool) -> (a -> String) -> IO a -> IO a
52 throwIf pred msgfct act =
53 do
54 res <- act
55 (if pred res then ioError . userError . msgfct else return) res
56
57 -- |Like 'throwIf', but discarding the result
58 --
59 throwIf_ :: (a -> Bool) -> (a -> String) -> IO a -> IO ()
60 throwIf_ pred msgfct act = void $ throwIf pred msgfct act
61
62 -- |Guards against negative result values
63 --
64 throwIfNeg :: (Ord a, Num a) => (a -> String) -> IO a -> IO a
65 throwIfNeg = throwIf (< 0)
66
67 -- |Like 'throwIfNeg', but discarding the result
68 --
69 throwIfNeg_ :: (Ord a, Num a) => (a -> String) -> IO a -> IO ()
70 throwIfNeg_ = throwIf_ (< 0)
71
72 -- |Guards against null pointers
73 --
74 throwIfNull :: String -> IO (Ptr a) -> IO (Ptr a)
75 throwIfNull = throwIf (== nullPtr) . const
76
77 -- |Discard the return value of an 'IO' action
78 --
79 void :: IO a -> IO ()
80 void act = act >> return ()