]> git.rkrishnan.org Git - functorrent.git/blob - src/FuncTorrent/Utils.hs
de2a4561c36f070c76841f944f0d134616943d19
[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 import qualified Data.ByteString.Char8 as BC (replicate)
17
18 splitN :: Int -> BC.ByteString -> [BC.ByteString]
19 splitN n bs | BC.null bs = []
20             | otherwise = BC.take n bs : splitN n (BC.drop n bs)
21
22 splitNum :: Integer -> Integer -> [Integer]
23 splitNum n d | n == 0 = []
24              | n < d = [n]
25              | otherwise = d : splitNum (n - d) d
26
27 createDummyFile :: FilePath -> Int -> IO ()
28 createDummyFile path size = do
29   dfe <- doesFileExist path
30   if dfe
31     then return ()
32     else
33     writeFile path (BC.replicate size '\0')
34
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
40                                   hPut h block)
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))