]> git.rkrishnan.org Git - functorrent.git/blob - src/FuncTorrent/Utils.hs
rename tracker response function, Utils, catch exceptions.
[functorrent.git] / src / FuncTorrent / Utils.hs
1 module FuncTorrent.Utils
2        (createDummyFile,
3         writeFileAtOffset,
4         readFileAtOffset,
5         splitNum,
6         splitN,
7         verifyHash
8        )
9        where
10
11 import Prelude hiding (writeFile, take)
12
13 import qualified Crypto.Hash.SHA1 as SHA1 (hash)
14 import Control.Exception.Base (IOException, try)
15 import Data.ByteString (ByteString, writeFile, hPut, hGet, take)
16 import qualified Data.ByteString.Char8 as BC
17 import System.IO (withFile, hSeek, IOMode(..), SeekMode(..))
18 import System.Directory (doesFileExist)
19
20 splitN :: Int -> BC.ByteString -> [BC.ByteString]
21 splitN n bs | BC.null bs = []
22             | otherwise = BC.take n bs : splitN n (BC.drop n bs)
23
24 splitNum :: Integer -> Integer -> [Integer]
25 splitNum n d | n == 0 = []
26              | n < d = [n]
27              | otherwise = d : splitNum (n - d) d
28
29 createDummyFile :: FilePath -> Int -> IO (Either IOException ())
30 createDummyFile path size = do
31   dfe <- doesFileExist path
32   if not dfe
33     then do
34     try $ writeFile path (BC.replicate size '\0')
35     else
36     return $ Right ()
37
38 -- write into a file at a specific offet
39 writeFileAtOffset :: FilePath -> Integer -> ByteString -> IO ()
40 writeFileAtOffset path offset block =
41   withFile path ReadWriteMode (\h -> do
42                                   hSeek h AbsoluteSeek offset
43                                   hPut h block)
44 readFileAtOffset :: FilePath -> Integer -> Integer -> IO ByteString
45 readFileAtOffset path offset len =
46   withFile path ReadWriteMode (\h -> do
47                                   hSeek h AbsoluteSeek offset
48                                   hGet h (fromInteger len))
49
50 verifyHash :: ByteString -> ByteString -> Bool
51 verifyHash bs pieceHash =
52   take 20 (SHA1.hash bs) == pieceHash