-- | Some helpers for dealing with WAI 'Header's.

module Network.Wai.Header
    ( contentLength
    ) where

import qualified Data.ByteString.Char8 as S8
import Network.HTTP.Types as H

-- | More useful for a response. A Wai Request already has a requestBodyLength
contentLength :: [(HeaderName, S8.ByteString)] -> Maybe Integer
contentLength :: [(HeaderName, ByteString)] -> Maybe Integer
contentLength [(HeaderName, ByteString)]
hdrs = HeaderName -> [(HeaderName, ByteString)] -> Maybe ByteString
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup HeaderName
H.hContentLength [(HeaderName, ByteString)]
hdrs Maybe ByteString -> (ByteString -> Maybe Integer) -> Maybe Integer
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= ByteString -> Maybe Integer
readInt

readInt :: S8.ByteString -> Maybe Integer
readInt :: ByteString -> Maybe Integer
readInt ByteString
bs =
    case ByteString -> Maybe (Integer, ByteString)
S8.readInteger ByteString
bs of
        Just (Integer
i, ByteString
rest) | ByteString -> Bool
S8.null ByteString
rest -> Integer -> Maybe Integer
forall a. a -> Maybe a
Just Integer
i
        Maybe (Integer, ByteString)
_ -> Maybe Integer
forall a. Maybe a
Nothing