]> git.rkrishnan.org Git - functorrent.git/blob - src/FuncTorrent/Utils.hs
48ebe67710d81258b9600c874dec3de414d52cf5
[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 Data.ByteString (ByteString, writeFile, hPut, hGet, take)
15 import qualified Data.ByteString.Char8 as BC
16 import System.IO (withFile, hSeek, IOMode(..), SeekMode(..))
17 import System.Directory (doesFileExist)
18
19 splitN :: Int -> BC.ByteString -> [BC.ByteString]
20 splitN n bs | BC.null bs = []
21             | otherwise = BC.take n bs : splitN n (BC.drop n bs)
22
23 splitNum :: Integer -> Integer -> [Integer]
24 splitNum n d | n == 0 = []
25              | n < d = [n]
26              | otherwise = d : splitNum (n - d) d
27
28 createDummyFile :: FilePath -> Int -> IO ()
29 createDummyFile path size = do
30   dfe <- doesFileExist path
31   if dfe
32     then return ()
33     else
34     writeFile path (BC.replicate size '\0')
35
36 -- write into a file at a specific offet
37 writeFileAtOffset :: FilePath -> Integer -> ByteString -> IO ()
38 writeFileAtOffset path offset block =
39   withFile path ReadWriteMode (\h -> do
40                                   hSeek h AbsoluteSeek offset
41                                   hPut h block)
42 readFileAtOffset :: FilePath -> Integer -> Integer -> IO ByteString
43 readFileAtOffset path offset len =
44   withFile path ReadWriteMode (\h -> do
45                                   hSeek h AbsoluteSeek offset
46                                   hGet h (fromInteger len))
47
48 verifyHash :: ByteString -> ByteString -> Bool
49 verifyHash bs pieceHash =
50   take 20 (SHA1.hash bs) == pieceHash