Avoid using deprecated flags
[packages/base.git] / Foreign / Marshal / Error.hs
1 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
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 -- Routines for testing return values and raising a 'userError' exception
13 -- in case of values indicating an error state.
14 --
15 -----------------------------------------------------------------------------
16
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)
25
26 -- Discard return value
27 --
28 void -- IO a -> IO ()
29 ) where
30
31 import Foreign.Ptr
32
33 #ifdef __GLASGOW_HASKELL__
34 #ifdef __HADDOCK__
35 import Data.Bool
36 import System.IO.Error
37 #endif
38 import GHC.Base
39 import GHC.Num
40 import GHC.IOBase
41 #endif
42
43 -- exported functions
44 -- ------------------
45
46 -- |Execute an 'IO' action, throwing a 'userError' if the predicate yields
47 -- 'True' when applied to the result returned by the 'IO' action.
48 -- If no exception is raised, return the result of the computation.
49 --
50 throwIf :: (a -> Bool) -- ^ error condition on the result of the 'IO' action
51 -> (a -> String) -- ^ computes an error message from erroneous results
52 -- of the 'IO' action
53 -> IO a -- ^ the 'IO' action to be executed
54 -> IO a
55 throwIf pred msgfct act =
56 do
57 res <- act
58 (if pred res then ioError . userError . msgfct else return) res
59
60 -- |Like 'throwIf', but discarding the result
61 --
62 throwIf_ :: (a -> Bool) -> (a -> String) -> IO a -> IO ()
63 throwIf_ pred msgfct act = void $ throwIf pred msgfct act
64
65 -- |Guards against negative result values
66 --
67 throwIfNeg :: (Ord a, Num a) => (a -> String) -> IO a -> IO a
68 throwIfNeg = throwIf (< 0)
69
70 -- |Like 'throwIfNeg', but discarding the result
71 --
72 throwIfNeg_ :: (Ord a, Num a) => (a -> String) -> IO a -> IO ()
73 throwIfNeg_ = throwIf_ (< 0)
74
75 -- |Guards against null pointers
76 --
77 throwIfNull :: String -> IO (Ptr a) -> IO (Ptr a)
78 throwIfNull = throwIf (== nullPtr) . const
79
80 -- |Discard the return value of an 'IO' action
81 --
82 void :: IO a -> IO ()
83 void act = act >> return ()