File: ReadN.hs

package info (click to toggle)
haskell-http2 5.0.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 55,180 kB
  • sloc: haskell: 8,657; makefile: 5
file content (40 lines) | stat: -rw-r--r-- 1,217 bytes parent folder | download
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
module Network.HTTP2.H2.ReadN where

import qualified Data.ByteString as B
import Data.IORef
import Network.Socket
import qualified Network.Socket.ByteString as N

-- | Naive implementation for readN.
defaultReadN :: Socket -> IORef (Maybe B.ByteString) -> Int -> IO B.ByteString
defaultReadN _ _ 0 = return B.empty
defaultReadN s ref n = do
    mbs <- readIORef ref
    writeIORef ref Nothing
    case mbs of
        Nothing -> do
            bs <- N.recv s n
            if B.null bs
                then return B.empty
                else
                    if B.length bs == n
                        then return bs
                        else loop bs
        Just bs
            | B.length bs == n -> return bs
            | B.length bs > n -> do
                let (bs0, bs1) = B.splitAt n bs
                writeIORef ref (Just bs1)
                return bs0
            | otherwise -> loop bs
  where
    loop bs = do
        let n' = n - B.length bs
        bs1 <- N.recv s n'
        if B.null bs1
            then return B.empty
            else do
                let bs2 = bs `B.append` bs1
                if B.length bs2 == n
                    then return bs2
                    else loop bs2