1 {-# OPTIONS -fno-implicit-prelude #-}
2 -----------------------------------------------------------------------------
4 -- Module : Foreign.Marshal.Error
5 -- Copyright : (c) The FFI task force 2001
6 -- License : BSD-style (see the file libraries/base/LICENSE)
8 -- Maintainer : ffi@haskell.org
9 -- Stability : provisional
10 -- Portability : portable
12 -- Marshalling support: Handling of common error conditions
14 -----------------------------------------------------------------------------
16 module Foreign.Marshal.Error (
19 -- |Throw an exception on specific return values
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)
29 -- Discard return value
36 #ifdef __GLASGOW_HASKELL__
45 -- |Guard an 'IO' operation and throw an exception if the result meets the given
48 -- * the second argument computes an error message from the result of the 'IO'
51 throwIf :: (a -> Bool) -> (a -> String) -> IO a -> IO a
52 throwIf pred msgfct act =
55 (if pred res then ioError . userError . msgfct else return) res
57 -- |Like 'throwIf', but discarding the result
59 throwIf_ :: (a -> Bool) -> (a -> String) -> IO a -> IO ()
60 throwIf_ pred msgfct act = void $ throwIf pred msgfct act
62 -- |Guards against negative result values
64 throwIfNeg :: (Ord a, Num a) => (a -> String) -> IO a -> IO a
65 throwIfNeg = throwIf (< 0)
67 -- |Like 'throwIfNeg', but discarding the result
69 throwIfNeg_ :: (Ord a, Num a) => (a -> String) -> IO a -> IO ()
70 throwIfNeg_ = throwIf_ (< 0)
72 -- |Guards against null pointers
74 throwIfNull :: String -> IO (Ptr a) -> IO (Ptr a)
75 throwIfNull = throwIf (== nullPtr) . const
77 -- |Discard the return value of an 'IO' action
80 void act = act >> return ()