]> git.rkrishnan.org Git - functorrent.git/blobdiff - src/FuncTorrent/Utils.hs
rename tracker response function, Utils, catch exceptions.
[functorrent.git] / src / FuncTorrent / Utils.hs
index de2a4561c36f070c76841f944f0d134616943d19..2a2797626527c8bdc7f3f983361bed31f127e129 100644 (file)
@@ -3,17 +3,19 @@ module FuncTorrent.Utils
         writeFileAtOffset,
         readFileAtOffset,
         splitNum,
-        splitN
+        splitN,
+        verifyHash
        )
        where
 
-import Prelude hiding (writeFile)
+import Prelude hiding (writeFile, take)
 
+import qualified Crypto.Hash.SHA1 as SHA1 (hash)
+import Control.Exception.Base (IOException, try)
+import Data.ByteString (ByteString, writeFile, hPut, hGet, take)
+import qualified Data.ByteString.Char8 as BC
 import System.IO (withFile, hSeek, IOMode(..), SeekMode(..))
 import System.Directory (doesFileExist)
-import Data.ByteString (ByteString, writeFile, hPut, hGet)
-import qualified Data.ByteString.Char8 as BC
-import qualified Data.ByteString.Char8 as BC (replicate)
 
 splitN :: Int -> BC.ByteString -> [BC.ByteString]
 splitN n bs | BC.null bs = []
@@ -24,13 +26,14 @@ splitNum n d | n == 0 = []
              | n < d = [n]
              | otherwise = d : splitNum (n - d) d
 
-createDummyFile :: FilePath -> Int -> IO ()
+createDummyFile :: FilePath -> Int -> IO (Either IOException ())
 createDummyFile path size = do
   dfe <- doesFileExist path
-  if dfe
-    then return ()
+  if not dfe
+    then do
+    try $ writeFile path (BC.replicate size '\0')
     else
-    writeFile path (BC.replicate size '\0')
+    return $ Right ()
 
 -- write into a file at a specific offet
 writeFileAtOffset :: FilePath -> Integer -> ByteString -> IO ()
@@ -43,3 +46,7 @@ readFileAtOffset path offset len =
   withFile path ReadWriteMode (\h -> do
                                   hSeek h AbsoluteSeek offset
                                   hGet h (fromInteger len))
+
+verifyHash :: ByteString -> ByteString -> Bool
+verifyHash bs pieceHash =
+  take 20 (SHA1.hash bs) == pieceHash