f65e055c495d584834799c61426f2ec891438ab7
[ghc-base.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/core/LICENSE)
7 -- 
8 -- Maintainer  :  ffi@haskell.org
9 -- Stability   :  provisional
10 -- Portability :  portable
11 --
12 -- $Id: Error.hs,v 1.2 2001/07/03 11:37:50 simonmar Exp $
13 --
14 -- Marshalling support: Handling of common error conditions
15 --
16 -----------------------------------------------------------------------------
17
18 module Foreign.Marshal.Error (
19
20   -- throw an exception on specific return values
21   --
22   throwIf,       -- :: (a -> Bool) -> (a -> String) -> IO a       -> IO a
23   throwIf_,      -- :: (a -> Bool) -> (a -> String) -> IO a       -> IO ()
24   throwIfNeg,    -- :: (Ord a, Num a) 
25                  -- =>                (a -> String) -> IO a       -> IO a
26   throwIfNeg_,   -- :: (Ord a, Num a)
27                  -- =>                (a -> String) -> IO a       -> IO ()
28   throwIfNull,   -- ::                String        -> IO (Ptr a) -> IO (Ptr a)
29
30   -- discard return value
31   --
32   void           -- IO a -> IO ()
33 ) where
34
35 import Foreign.Ptr
36
37 #ifdef __GLASGOW_HASKELL__
38 import GHC.Base
39 import GHC.Num
40 import GHC.IOBase
41 #endif
42
43 -- exported functions
44 -- ------------------
45
46 -- guard an IO operation and throw an exception if the result meets the given
47 -- predicate 
48 --
49 -- * the second argument computes an error message from the result of the IO
50 --   operation
51 --
52 throwIf                 :: (a -> Bool) -> (a -> String) -> IO a -> IO a
53 throwIf pred msgfct act  = 
54   do
55     res <- act
56     (if pred res then ioError . userError . msgfct else return) res
57
58 -- like `throwIf', but discarding the result
59 --
60 throwIf_                 :: (a -> Bool) -> (a -> String) -> IO a -> IO ()
61 throwIf_ pred msgfct act  = void $ throwIf pred msgfct act
62
63 -- guards against negative result values
64 --
65 throwIfNeg :: (Ord a, Num a) => (a -> String) -> IO a -> IO a
66 throwIfNeg  = throwIf (< 0)
67
68 -- like `throwIfNeg', but discarding the result
69 --
70 throwIfNeg_ :: (Ord a, Num a) => (a -> String) -> IO a -> IO ()
71 throwIfNeg_  = throwIf_ (< 0)
72
73 -- guards against null pointers
74 --
75 throwIfNull :: String -> IO (Ptr a) -> IO (Ptr a)
76 throwIfNull  = throwIf (== nullPtr) . const
77
78 -- discard the return value of an IO action
79 --
80 void     :: IO a -> IO ()
81 void act  = act >> return ()