{-# LINE 1 "src/Happstack/Server/Internal/NoPush.hsc" #-}
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LINE 2 "src/Happstack/Server/Internal/NoPush.hsc" #-}

module Happstack.Server.Internal.NoPush (setNoPush, withNoPush) where


{-# LINE 6 "src/Happstack/Server/Internal/NoPush.hsc" #-}

{-# LINE 7 "src/Happstack/Server/Internal/NoPush.hsc" #-}

{-# LINE 8 "src/Happstack/Server/Internal/NoPush.hsc" #-}

import Control.Exception (finally)
import Foreign.C.Error (throwErrnoIfMinus1_)
import Foreign.C.Types (CInt)
import Foreign.Marshal.Utils (with)
import Foreign.Ptr (Ptr)
import Foreign.Storable (sizeOf)
import Network.Socket (Socket(..))

withNoPush :: Socket -> IO a -> IO a
withNoPush sock act = setNoPush sock True >> act `finally` setNoPush sock False

noPush :: CInt

{-# LINE 24 "src/Happstack/Server/Internal/NoPush.hsc" #-}
noPush = 3
{-# LINE 25 "src/Happstack/Server/Internal/NoPush.hsc" #-}

{-# LINE 28 "src/Happstack/Server/Internal/NoPush.hsc" #-}

setNoPush :: Socket -> Bool -> IO ()
setNoPush _ _ | noPush == 0 = return ()
setNoPush (MkSocket fd _ _ _ _) onOff = do
  let v = if onOff then 1 else 0
  with v $ \ptr ->
    throwErrnoIfMinus1_ "setNoPush" $
      c_setsockopt fd (6) noPush ptr (fromIntegral (sizeOf v))
{-# LINE 36 "src/Happstack/Server/Internal/NoPush.hsc" #-}

foreign import ccall unsafe "setsockopt"
  c_setsockopt :: CInt -> CInt -> CInt -> Ptr CInt -> CInt -> IO CInt