1
+ {-# LANGUAGE BangPatterns #-}
1
2
{-# LANGUAGE RecordWildCards #-}
2
3
{-# LANGUAGE OverloadedStrings #-}
3
4
@@ -269,22 +270,23 @@ remainingChunks i (x:xs)
269
270
-- IOVec made from @cs@ and the number of pointers (@length cs@).
270
271
-- /Unix only/.
271
272
withIOVecfromBS :: [ByteString ] -> ((Ptr IOVec , Int ) -> IO a ) -> IO a
272
- withIOVecfromBS cs f = do
273
- bufsizs <- mapM getBufsiz cs
274
- withIOVec bufsizs f
273
+ withIOVecfromBS cs f = withBufSizs cs $ \ bufsizs -> withIOVec bufsizs f
275
274
#else
276
275
-- | @withWSABuffromBS cs f@ executes the computation @f@, passing as argument a pair
277
276
-- consisting of a pointer to a temporarily allocated array of pointers to
278
277
-- WSABuf made from @cs@ and the number of pointers (@length cs@).
279
278
-- /Windows only/.
280
279
withWSABuffromBS :: [ByteString ] -> ((Ptr WSABuf , Int ) -> IO a ) -> IO a
281
- withWSABuffromBS cs f = do
282
- bufsizs <- mapM getBufsiz cs
283
- withWSABuf bufsizs f
280
+ withWSABuffromBS cs f = withBufSizs cs $ \ bufsizs -> withWSABuf bufsizs f
284
281
#endif
285
282
286
- getBufsiz :: ByteString -> IO (Ptr Word8 , Int )
287
- getBufsiz (PS fptr off len) = withForeignPtr fptr $ \ ptr -> return (ptr `plusPtr` off, len)
283
+ withBufSizs :: [ByteString ] -> ([(Ptr Word8 , Int )] -> IO a ) -> IO a
284
+ withBufSizs bss0 f = loop bss0 id
285
+ where
286
+ loop [] ! build = f $ build []
287
+ loop (PS fptr off len: bss) ! build = withForeignPtr fptr $ \ ptr -> do
288
+ let ! ptr' = ptr `plusPtr` off
289
+ loop bss (build . ((ptr',len) : ))
288
290
289
291
-- | Send data to the socket using sendmsg(2).
290
292
sendMsg :: Socket -- ^ Socket
@@ -294,8 +296,7 @@ sendMsg :: Socket -- ^ Socket
294
296
-> MsgFlag -- ^ Message flags
295
297
-> IO Int -- ^ The length actually sent
296
298
sendMsg _ _ [] _ _ = return 0
297
- sendMsg s addr bss cmsgs flags = do
298
- bufsizs <- mapM getBufsiz bss
299
+ sendMsg s addr bss cmsgs flags = withBufSizs bss $ \ bufsizs ->
299
300
sendBufMsg s addr bufsizs cmsgs flags
300
301
301
302
-- | Receive data from the socket using recvmsg(2).
@@ -309,9 +310,9 @@ recvMsg :: Socket -- ^ Socket
309
310
-> MsgFlag -- ^ Message flags
310
311
-> IO (SockAddr , ByteString , [Cmsg ], MsgFlag ) -- ^ Source address, received data, control messages and message flags
311
312
recvMsg s siz clen flags = do
312
- bs <- create siz $ \ ptr -> zeroMemory ptr (fromIntegral siz)
313
- bufsiz <- getBufsiz bs
314
- (addr,len,cmsgs,flags') <- recvBufMsg s [bufsiz ] clen flags
315
- let bs' | len < siz = let PS buf 0 _ = bs in PS buf 0 len
316
- | otherwise = bs
317
- return (addr, bs', cmsgs, flags')
313
+ bs@ ( PS fptr _ _) <- create siz $ \ ptr -> zeroMemory ptr (fromIntegral siz)
314
+ withForeignPtr fptr $ \ ptr -> do
315
+ (addr,len,cmsgs,flags') <- recvBufMsg s [(ptr,siz) ] clen flags
316
+ let bs' | len < siz = PS fptr 0 len
317
+ | otherwise = bs
318
+ return (addr, bs', cmsgs, flags')
0 commit comments