From a899bd3f7fef500c040feb985c69a18dfc567bac Mon Sep 17 00:00:00 2001
From: Ramakrishnan Muthukrishnan <ram@rkrishnan.org>
Date: Fri, 24 Jul 2015 20:09:54 +0530
Subject: [PATCH] writeFileAtOffset: name says it all

Perhaps this should be moved to Util module.
---
 src/FuncTorrent/Peer.hs | 11 +++++++++--
 1 file changed, 9 insertions(+), 2 deletions(-)

diff --git a/src/FuncTorrent/Peer.hs b/src/FuncTorrent/Peer.hs
index b9138b7..ae768a8 100644
--- a/src/FuncTorrent/Peer.hs
+++ b/src/FuncTorrent/Peer.hs
@@ -6,7 +6,7 @@ module FuncTorrent.Peer
 
 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)
@@ -188,7 +188,13 @@ createDummyFile :: FilePath -> Int -> IO ()
 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 &&
@@ -208,6 +214,7 @@ msgLoop pState pieceStatus | meInterested pState == False &&
                                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)
-- 
2.45.2