File: Fallback.hs

package info (click to toggle)
haskell-simple-sendfile 0.2.32-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,104 kB
  • sloc: haskell: 324; makefile: 6
file content (51 lines) | stat: -rw-r--r-- 1,569 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
{-# LANGUAGE CPP #-}
module Network.Sendfile.Fallback (
    sendfile
  , sendfileWithHeader
  ) where

import Control.Monad.IO.Class (MonadIO(liftIO))
import Data.ByteString (ByteString)
import Data.Conduit
import Data.Conduit.Binary as EB
import Network.Sendfile.Types
import Network.Socket
import Network.Socket.ByteString
import qualified Network.Socket.ByteString as SB

-- |
-- Sendfile emulation using conduit.
-- Used system calls:
--
--  - Used system calls: open(), stat(), read(), send() and close().

sendfile :: Socket -> FilePath -> FileRange -> IO () -> IO ()
sendfile sock path EntireFile hook =
    runConduitRes $ sourceFile path  .| sinkSocket sock hook
sendfile sock path (PartOfFile off len) hook =
    runConduitRes $ EB.sourceFileRange path (Just off) (Just len) .| sinkSocket sock hook

-- See sinkHandle.
sinkSocket :: MonadIO m => Socket -> IO () -> ConduitT ByteString Void m ()
#if MIN_VERSION_conduit(0,5,0)
sinkSocket s hook = awaitForever $ \bs -> liftIO $ SB.sendAll s bs >> hook
#else
sinkSocket s hook = NeedInput push close
  where
    push bs = flip PipeM (return ()) $ do
        liftIO (SB.sendAll s bs)
        liftIO hook
        return (NeedInput push close)
    close = return ()
#endif

-- |
-- Sendfile emulation using conduit.
-- Used system calls:
--
--  - Used system calls: open(), stat(), read(), writev(), send() and close().

sendfileWithHeader :: Socket -> FilePath -> FileRange -> IO () -> [ByteString] -> IO ()
sendfileWithHeader sock path range hook hdr = do
    sendMany sock hdr
    sendfile sock path range hook