1 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
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 -- Routines for testing return values and raising a 'userError' exception
13 -- in case of values indicating an error state.
15 -----------------------------------------------------------------------------
17 module Foreign.Marshal.Error (
18 throwIf, -- :: (a -> Bool) -> (a -> String) -> IO a -> IO a
19 throwIf_, -- :: (a -> Bool) -> (a -> String) -> IO a -> IO ()
20 throwIfNeg, -- :: (Ord a, Num a)
21 -- => (a -> String) -> IO a -> IO a
22 throwIfNeg_, -- :: (Ord a, Num a)
23 -- => (a -> String) -> IO a -> IO ()
24 throwIfNull, -- :: String -> IO (Ptr a) -> IO (Ptr a)
26 -- Discard return value
33 #ifdef __GLASGOW_HASKELL__
36 import System.IO.Error
41 import GHC.IO.Exception
47 -- |Execute an 'IO' action, throwing a 'userError' if the predicate yields
48 -- 'True' when applied to the result returned by the 'IO' action.
49 -- If no exception is raised, return the result of the computation.
51 throwIf :: (a -> Bool) -- ^ error condition on the result of the 'IO' action
52 -> (a -> String) -- ^ computes an error message from erroneous results
54 -> IO a -- ^ the 'IO' action to be executed
56 throwIf pred msgfct act =
59 (if pred res then ioError . userError . msgfct else return) res
61 -- |Like 'throwIf', but discarding the result
63 throwIf_ :: (a -> Bool) -> (a -> String) -> IO a -> IO ()
64 throwIf_ pred msgfct act = void $ throwIf pred msgfct act
66 -- |Guards against negative result values
68 throwIfNeg :: (Ord a, Num a) => (a -> String) -> IO a -> IO a
69 throwIfNeg = throwIf (< 0)
71 -- |Like 'throwIfNeg', but discarding the result
73 throwIfNeg_ :: (Ord a, Num a) => (a -> String) -> IO a -> IO ()
74 throwIfNeg_ = throwIf_ (< 0)
76 -- |Guards against null pointers
78 throwIfNull :: String -> IO (Ptr a) -> IO (Ptr a)
79 throwIfNull = throwIf (== nullPtr) . const
81 -- |Discard the return value of an 'IO' action
84 void act = act >> return ()