]> git.rkrishnan.org Git - functorrent.git/blob - src/FuncTorrent/Utils.hs
*.hs: add GPLv3 License text and copyright notice
[functorrent.git] / src / FuncTorrent / Utils.hs
1 {-
2 Copyright (C) 2015-2016 Ramakrishnan Muthukrishnan <ram@rkrishnan.org>
3
4 This file is part of FuncTorrent.
5
6 FuncTorrent is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
10
11 FuncTorrent is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with FuncTorrent; if not,  see <http://www.gnu.org/licenses/>
18 -}
19
20
21 module FuncTorrent.Utils
22        (createDummyFile,
23         writeFileAtOffset,
24         readFileAtOffset,
25         splitNum,
26         splitN,
27         verifyHash
28        )
29        where
30
31 import Prelude hiding (writeFile, take)
32
33 import qualified Crypto.Hash.SHA1 as SHA1 (hash)
34 import Control.Exception.Base (IOException, try)
35 import Data.ByteString (ByteString, writeFile, hPut, hGet, take)
36 import qualified Data.ByteString.Char8 as BC
37 import System.IO (Handle, hSeek, SeekMode(..))
38 import System.Directory (doesFileExist)
39
40 splitN :: Int -> BC.ByteString -> [BC.ByteString]
41 splitN n bs | BC.null bs = []
42             | otherwise = BC.take n bs : splitN n (BC.drop n bs)
43
44 splitNum :: Integer -> Integer -> [Integer]
45 splitNum n d | n == 0 = []
46              | n < d = [n]
47              | otherwise = d : splitNum (n - d) d
48
49 createDummyFile :: FilePath -> Int -> IO (Either IOException ())
50 createDummyFile path size = do
51   dfe <- doesFileExist path
52   if not dfe
53     then do
54     try $ writeFile path (BC.replicate size '\0')
55     else
56     return $ Right ()
57
58 -- write into a file at a specific offet
59 writeFileAtOffset :: Handle -> Integer -> ByteString -> IO ()
60 writeFileAtOffset h offset block = do
61   hSeek h AbsoluteSeek offset
62   hPut h block
63
64 readFileAtOffset :: Handle -> Integer -> Integer -> IO ByteString
65 readFileAtOffset h offset len = do
66   hSeek h AbsoluteSeek offset
67   hGet h (fromInteger len)
68
69 verifyHash :: ByteString -> ByteString -> Bool
70 verifyHash bs pieceHash =
71   take 20 (SHA1.hash bs) == pieceHash