Perhaps this should be moved to Util module.
import Prelude hiding (lookup, concat, replicate, splitAt, writeFile)
import Prelude hiding (lookup, concat, replicate, splitAt, writeFile)
-import System.IO (Handle, BufferMode(..), hSetBuffering)
+import System.IO (Handle, BufferMode(..), IOMode(..), SeekMode(..), withFile, hSeek, hSetBuffering)
import Data.ByteString (ByteString, pack, unpack, concat, hGet, hPut, singleton, writeFile)
import Data.ByteString.Lazy (fromStrict, fromChunks, toStrict)
import qualified Data.ByteString.Char8 as BC (replicate, pack, length)
import Data.ByteString (ByteString, pack, unpack, concat, hGet, hPut, singleton, writeFile)
import Data.ByteString.Lazy (fromStrict, fromChunks, toStrict)
import qualified Data.ByteString.Char8 as BC (replicate, pack, length)
createDummyFile path size =
writeFile path (BC.replicate size '\0')
createDummyFile path size =
writeFile path (BC.replicate size '\0')
--- loop1 :: shake hands with all peers, find out the pieces they have, form PieceData.
+-- write into a file at a specific offet
+writeFileAtOffset :: FilePath -> Integer -> ByteString -> IO ()
+writeFileAtOffset path offset block =
+ withFile path WriteMode $ (\h -> do
+ _ <- hSeek h AbsoluteSeek offset
+ hPut h block)
+
-- recvMsg :: Peer -> Handle -> Msg
msgLoop :: PeerState -> PieceMap -> IO ()
msgLoop pState pieceStatus | meInterested pState == False &&
-- recvMsg :: Peer -> Handle -> Msg
msgLoop :: PeerState -> PieceMap -> IO ()
msgLoop pState pieceStatus | meInterested pState == False &&
Just workPiece -> do
let pLen = len (pieceStatus ! workPiece)
_ <- downloadPiece (handle pState) workPiece pLen
Just workPiece -> do
let pLen = len (pieceStatus ! workPiece)
_ <- downloadPiece (handle pState) workPiece pLen
+ -- TODO: verify the hash
msgLoop pState (adjust (\pieceData -> pieceData { state = Have }) workPiece pieceStatus)
| otherwise = do
msg <- getMsg (handle pState)
msgLoop pState (adjust (\pieceData -> pieceData { state = Have }) workPiece pieceStatus)
| otherwise = do
msg <- getMsg (handle pState)