{-# LANGUAGE CPP #-}

module Network.Sendfile.Types where

import GHC.IO.Exception (IOErrorType(InvalidArgument), IOException(..))

#ifdef VERSION_unix
import qualified Data.ByteString as B

import qualified System.Posix.IO            as P
import qualified System.Posix.IO.ByteString as PB
import qualified System.Posix.Types         as P
#endif

-- |
--  File range for 'sendfile'.
--
--  * If the offset or the length of 'PartOfFile' is negative, an
--    'IOException' of 'InvalidArgument' is thrown before anything is sent.
--
--  * If the length is 0, nothing is sent (only the header for the
--    @WithHeader@ variants).
--
--  * If the file is shorter than the range, or is truncated while
--    being sent, sending stops at the end of the file without any
--    error. So, the number of bytes sent may be less than requested.

data FileRange = EntireFile
               | PartOfFile {
                   FileRange -> Integer
rangeOffset :: Integer
                 , FileRange -> Integer
rangeLength :: Integer
                 }

-- | Throws 'InvalidArgument' if the offset or the length is negative.
checkRange :: FileRange -> IO ()
checkRange :: FileRange -> IO ()
checkRange (PartOfFile Integer
off Integer
len)
  | Integer
off Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
< Integer
0 Bool -> Bool -> Bool
|| Integer
len Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
< Integer
0 = IOError -> IO ()
forall a. HasCallStack => IOError -> IO a
ioError (IOError -> IO ()) -> IOError -> IO ()
forall a b. (a -> b) -> a -> b
$ Maybe Handle
-> IOErrorType
-> String
-> String
-> Maybe CInt
-> Maybe String
-> IOError
IOError Maybe Handle
forall a. Maybe a
Nothing IOErrorType
InvalidArgument
        String
"Network.Sendfile" String
"negative offset or length" Maybe CInt
forall a. Maybe a
Nothing Maybe String
forall a. Maybe a
Nothing
checkRange FileRange
_ = () -> IO ()
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ()

-- To avoid build error in windows
#ifdef VERSION_unix

-- | 'openFd's signature changed in @unix-2.8@. This is a portable wrapper.
openFd :: FilePath -> P.OpenMode -> P.OpenFileFlags -> IO P.Fd
#if MIN_VERSION_unix(2,8,0)
openFd :: String -> OpenMode -> OpenFileFlags -> IO Fd
openFd String
path OpenMode
mode OpenFileFlags
flags = String -> OpenMode -> OpenFileFlags -> IO Fd
P.openFd String
path OpenMode
mode OpenFileFlags
flags
#else
openFd path mode flags = P.openFd path mode Nothing flags
#endif

-- | 'openFd's signature changed in @unix-2.8@. This is a portable wrapper.
openFdBS :: B.ByteString -> P.OpenMode -> P.OpenFileFlags -> IO P.Fd
#if MIN_VERSION_unix(2,8,0)
openFdBS :: ByteString -> OpenMode -> OpenFileFlags -> IO Fd
openFdBS ByteString
path OpenMode
mode OpenFileFlags
flags = ByteString -> OpenMode -> OpenFileFlags -> IO Fd
PB.openFd ByteString
path OpenMode
mode OpenFileFlags
flags
#else
openFdBS path mode flags = PB.openFd path mode Nothing flags
#endif

#endif