1 module FuncTorrent.Utils
11 import Prelude hiding (writeFile, take)
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)
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)
23 splitNum :: Integer -> Integer -> [Integer]
24 splitNum n d | n == 0 = []
26 | otherwise = d : splitNum (n - d) d
28 createDummyFile :: FilePath -> Int -> IO ()
29 createDummyFile path size = do
30 dfe <- doesFileExist path
34 writeFile path (BC.replicate size '\0')
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
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))
48 verifyHash :: ByteString -> ByteString -> Bool
49 verifyHash bs pieceHash =
50 take 20 (SHA1.hash bs) == pieceHash