module Network.HTTP2.H2.Config where

import Data.IORef
import Foreign.Marshal.Alloc (free, mallocBytes)
import Network.HTTP.Semantics.Client
import Network.Socket
import Network.Socket.ByteString (sendAll)
import qualified System.TimeManager as T

import Network.HPACK
import Network.HTTP2.H2.Types

-- | Making simple configuration whose IO is not efficient.
--   A write buffer is allocated internally.
allocSimpleConfig :: Socket -> BufferSize -> IO Config
allocSimpleConfig :: Socket -> Int -> IO Config
allocSimpleConfig Socket
s Int
bufsiz = do
    Ptr Word8
buf <- Int -> IO (Ptr Word8)
forall a. Int -> IO (Ptr a)
mallocBytes Int
bufsiz
    IORef (Maybe ByteString)
ref <- Maybe ByteString -> IO (IORef (Maybe ByteString))
forall a. a -> IO (IORef a)
newIORef Maybe ByteString
forall a. Maybe a
Nothing
    Manager
timmgr <- Int -> IO Manager
T.initialize (Int -> IO Manager) -> Int -> IO Manager
forall a b. (a -> b) -> a -> b
$ Int
30 Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
1000000
    SockAddr
mysa <- Socket -> IO SockAddr
getSocketName Socket
s
    SockAddr
peersa <- Socket -> IO SockAddr
getPeerName Socket
s
    let config :: Config
config =
            Config
                { confWriteBuffer :: Ptr Word8
confWriteBuffer = Ptr Word8
buf
                , confBufferSize :: Int
confBufferSize = Int
bufsiz
                , confSendAll :: ByteString -> IO ()
confSendAll = Socket -> ByteString -> IO ()
sendAll Socket
s
                , confReadN :: Int -> IO ByteString
confReadN = Socket -> IORef (Maybe ByteString) -> Int -> IO ByteString
defaultReadN Socket
s IORef (Maybe ByteString)
ref
                , confPositionReadMaker :: PositionReadMaker
confPositionReadMaker = PositionReadMaker
defaultPositionReadMaker
                , confTimeoutManager :: Manager
confTimeoutManager = Manager
timmgr
                , confMySockAddr :: SockAddr
confMySockAddr = SockAddr
mysa
                , confPeerSockAddr :: SockAddr
confPeerSockAddr = SockAddr
peersa
                }
    Config -> IO Config
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Config
config

-- | Deallocating the resource of the simple configuration.
freeSimpleConfig :: Config -> IO ()
freeSimpleConfig :: Config -> IO ()
freeSimpleConfig Config
conf = do
    Ptr Word8 -> IO ()
forall a. Ptr a -> IO ()
free (Ptr Word8 -> IO ()) -> Ptr Word8 -> IO ()
forall a b. (a -> b) -> a -> b
$ Config -> Ptr Word8
confWriteBuffer Config
conf
    Manager -> IO ()
T.killManager (Manager -> IO ()) -> Manager -> IO ()
forall a b. (a -> b) -> a -> b
$ Config -> Manager
confTimeoutManager Config
conf