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