SafeHaskell: Added SafeHaskell to base
[ghc.git] / libraries / base / Foreign / Marshal / Error.hs
1 {-# LANGUAGE Trustworthy #-}
2 {-# LANGUAGE CPP, NoImplicitPrelude #-}
3
4 -----------------------------------------------------------------------------
5 -- |
6 -- Module : Foreign.Marshal.Error
7 -- Copyright : (c) The FFI task force 2001
8 -- License : BSD-style (see the file libraries/base/LICENSE)
9 --
10 -- Maintainer : ffi@haskell.org
11 -- Stability : provisional
12 -- Portability : portable
13 --
14 -- Routines for testing return values and raising a 'userError' exception
15 -- in case of values indicating an error state.
16 --
17 -----------------------------------------------------------------------------
18
19 module Foreign.Marshal.Error (
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 #ifdef __HADDOCK__
37 import Data.Bool
38 import System.IO.Error
39 #endif
40 import GHC.Base
41 import GHC.Num
42 import GHC.IO.Exception
43 #endif
44
45 -- exported functions
46 -- ------------------
47
48 -- |Execute an 'IO' action, throwing a 'userError' if the predicate yields
49 -- 'True' when applied to the result returned by the 'IO' action.
50 -- If no exception is raised, return the result of the computation.
51 --
52 throwIf :: (a -> Bool) -- ^ error condition on the result of the 'IO' action
53 -> (a -> String) -- ^ computes an error message from erroneous results
54 -- of the 'IO' action
55 -> IO a -- ^ the 'IO' action to be executed
56 -> IO a
57 throwIf pred msgfct act =
58 do
59 res <- act
60 (if pred res then ioError . userError . msgfct else return) res
61
62 -- |Like 'throwIf', but discarding the result
63 --
64 throwIf_ :: (a -> Bool) -> (a -> String) -> IO a -> IO ()
65 throwIf_ pred msgfct act = void $ throwIf pred msgfct act
66
67 -- |Guards against negative result values
68 --
69 throwIfNeg :: (Ord a, Num a) => (a -> String) -> IO a -> IO a
70 throwIfNeg = throwIf (< 0)
71
72 -- |Like 'throwIfNeg', but discarding the result
73 --
74 throwIfNeg_ :: (Ord a, Num a) => (a -> String) -> IO a -> IO ()
75 throwIfNeg_ = throwIf_ (< 0)
76
77 -- |Guards against null pointers
78 --
79 throwIfNull :: String -> IO (Ptr a) -> IO (Ptr a)
80 throwIfNull = throwIf (== nullPtr) . const
81
82 -- |Discard the return value of an 'IO' action
83 --
84 void :: IO a -> IO ()
85 void act = act >> return ()