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