Error.hs 2.21 KB
Newer Older
1
{-# LANGUAGE Trustworthy #-}
2
3
{-# LANGUAGE CPP, NoImplicitPrelude #-}

4
-----------------------------------------------------------------------------
5
-- |
6
7
-- Module      :  Foreign.Marshal.Error
-- Copyright   :  (c) The FFI task force 2001
8
-- License     :  BSD-style (see the file libraries/base/LICENSE)
9
10
-- 
-- Maintainer  :  ffi@haskell.org
11
12
-- Stability   :  provisional
-- Portability :  portable
13
--
ross's avatar
ross committed
14
15
-- Routines for testing return values and raising a 'userError' exception
-- in case of values indicating an error state.
16
17
18
19
--
-----------------------------------------------------------------------------

module Foreign.Marshal.Error (
20
21
22
23
24
  throwIf,
  throwIf_,
  throwIfNeg,
  throwIfNeg_,
  throwIfNull,
25

26
  -- Discard return value
27
  --
28
  void
29
30
31
32
33
34
) where

import Foreign.Ptr

import GHC.Base
import GHC.Num
35
import GHC.IO.Exception
36
37
38
39

-- exported functions
-- ------------------

ross's avatar
ross committed
40
41
42
-- |Execute an 'IO' action, throwing a 'userError' if the predicate yields
-- 'True' when applied to the result returned by the 'IO' action.
-- If no exception is raised, return the result of the computation.
43
--
Don Stewart's avatar
Don Stewart committed
44
45
46
47
48
throwIf :: (a -> Bool)  -- ^ error condition on the result of the 'IO' action
        -> (a -> String) -- ^ computes an error message from erroneous results
                        -- of the 'IO' action
        -> IO a         -- ^ the 'IO' action to be executed
        -> IO a
49
50
51
52
53
throwIf pred msgfct act  = 
  do
    res <- act
    (if pred res then ioError . userError . msgfct else return) res

54
-- |Like 'throwIf', but discarding the result
55
56
57
58
--
throwIf_                 :: (a -> Bool) -> (a -> String) -> IO a -> IO ()
throwIf_ pred msgfct act  = void $ throwIf pred msgfct act

59
-- |Guards against negative result values
60
61
62
63
--
throwIfNeg :: (Ord a, Num a) => (a -> String) -> IO a -> IO a
throwIfNeg  = throwIf (< 0)

64
-- |Like 'throwIfNeg', but discarding the result
65
66
67
68
--
throwIfNeg_ :: (Ord a, Num a) => (a -> String) -> IO a -> IO ()
throwIfNeg_  = throwIf_ (< 0)

69
-- |Guards against null pointers
70
71
72
73
--
throwIfNull :: String -> IO (Ptr a) -> IO (Ptr a)
throwIfNull  = throwIf (== nullPtr) . const

74
-- |Discard the return value of an 'IO' action
75
76
77
--
void     :: IO a -> IO ()
void act  = act >> return ()
78
{-# DEPRECATED void "use 'Control.Monad.void' instead" #-} -- deprecated in 7.6