{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}

module Network.Wai.Handler.Warp.IO where

import Data.ByteString.Builder (Builder)
import Data.ByteString.Builder.Extra (runBuilder, Next(Done, More, Chunk))

import Network.Wai.Handler.Warp.Buffer
import Network.Wai.Handler.Warp.Imports
import Network.Wai.Handler.Warp.Types

toBufIOWith :: Buffer -> BufSize -> (ByteString -> IO ()) -> Builder -> IO ()
toBufIOWith :: Buffer -> BufSize -> (ByteString -> IO ()) -> Builder -> IO ()
toBufIOWith Buffer
buf !BufSize
size ByteString -> IO ()
io Builder
builder = BufferWriter -> IO ()
loop BufferWriter
firstWriter
  where
    firstWriter :: BufferWriter
firstWriter = Builder -> BufferWriter
runBuilder Builder
builder
    runIO :: BufSize -> IO ()
runIO BufSize
len = Buffer -> BufSize -> (ByteString -> IO ()) -> IO ()
bufferIO Buffer
buf BufSize
len ByteString -> IO ()
io
    loop :: BufferWriter -> IO ()
loop BufferWriter
writer = do
        (BufSize
len, Next
signal) <- BufferWriter
writer Buffer
buf BufSize
size
        case Next
signal of
             Next
Done -> BufSize -> IO ()
runIO BufSize
len
             More BufSize
minSize BufferWriter
next
               | BufSize
size BufSize -> BufSize -> Bool
forall a. Ord a => a -> a -> Bool
< BufSize
minSize -> [Char] -> IO ()
forall a. HasCallStack => [Char] -> a
error [Char]
"toBufIOWith: BufferFull: minSize"
               | Bool
otherwise      -> do
                   BufSize -> IO ()
runIO BufSize
len
                   BufferWriter -> IO ()
loop BufferWriter
next
             Chunk ByteString
bs BufferWriter
next -> do
                 BufSize -> IO ()
runIO BufSize
len
                 ByteString -> IO ()
io ByteString
bs
                 BufferWriter -> IO ()
loop BufferWriter
next