1 module FuncTorrent.Utils
11 import Prelude hiding (writeFile, take)
13 import qualified Crypto.Hash.SHA1 as SHA1 (hash)
14 import Control.Monad (unless)
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)
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)
24 splitNum :: Integer -> Integer -> [Integer]
25 splitNum n d | n == 0 = []
27 | otherwise = d : splitNum (n - d) d
29 createDummyFile :: FilePath -> Int -> IO ()
30 createDummyFile path size = do
31 dfe <- doesFileExist path
33 writeFile path (BC.replicate size '\0')
35 -- write into a file at a specific offet
36 writeFileAtOffset :: FilePath -> Integer -> ByteString -> IO ()
37 writeFileAtOffset path offset block =
38 withFile path ReadWriteMode (\h -> do
39 hSeek h AbsoluteSeek offset
41 readFileAtOffset :: FilePath -> Integer -> Integer -> IO ByteString
42 readFileAtOffset path offset len =
43 withFile path ReadWriteMode (\h -> do
44 hSeek h AbsoluteSeek offset
45 hGet h (fromInteger len))
47 verifyHash :: ByteString -> ByteString -> Bool
48 verifyHash bs pieceHash =
49 take 20 (SHA1.hash bs) == pieceHash