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