summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSam T <sta.cs.vsu@gmail.com>2013-04-20 23:50:45 +0400
committerSam T <sta.cs.vsu@gmail.com>2013-04-20 23:50:45 +0400
commit08bb327005c2f0dc517d0a74cf29e9f7f9b08e21 (patch)
tree5d3b369e0d9e63f0b351e48cfbcbc7fff1547b82
parent482f4f28b106d08ed20843a81c93efd3995e1439 (diff)
+ Add some block functions.
-rw-r--r--src/Network/Torrent/PeerWire/Block.hs41
1 files changed, 40 insertions, 1 deletions
diff --git a/src/Network/Torrent/PeerWire/Block.hs b/src/Network/Torrent/PeerWire/Block.hs
index b2fe8c31..056f6b18 100644
--- a/src/Network/Torrent/PeerWire/Block.hs
+++ b/src/Network/Torrent/PeerWire/Block.hs
@@ -1,8 +1,14 @@
1module Network.Torrent.PeerWire.Block 1module Network.Torrent.PeerWire.Block
2 ( BlockIx(..), Block(..) 2 ( BlockIx(..), Block(..)
3 , defaultBlockSize
4 , blockRange, ixRange, pieceIx
5 , isPiece
3 ) where 6 ) where
4 7
5import Data.ByteString (ByteString) 8import Data.ByteString (ByteString)
9import qualified Data.ByteString as B
10import Data.Int
11
6 12
7data BlockIx = BlockIx { 13data BlockIx = BlockIx {
8 ixPiece :: {-# UNPACK #-} !Int -- ^ Zero-based piece index. 14 ixPiece :: {-# UNPACK #-} !Int -- ^ Zero-based piece index.
@@ -15,3 +21,36 @@ data Block = Block {
15 , blkOffset :: Int -- ^ Zero-based byte offset within the piece. 21 , blkOffset :: Int -- ^ Zero-based byte offset within the piece.
16 , blkData :: ByteString -- ^ Payload. 22 , blkData :: ByteString -- ^ Payload.
17 } deriving (Show, Eq) 23 } deriving (Show, Eq)
24
25
26-- | Widely used semi-official block size.
27defaultBlockSize :: Int
28defaultBlockSize = 16 * 1024
29
30
31isPiece :: Int -> Block -> Bool
32isPiece pieceSize (Block i offset bs) =
33 offset == 0 && B.length bs == pieceSize && i >= 0
34{-# INLINE isPiece #-}
35
36pieceIx :: Int -> Int -> BlockIx
37pieceIx i = BlockIx i 0
38{-# INLINE pieceIx #-}
39
40blockRange :: (Num a, Integral a) => Int -> Block -> (a, a)
41blockRange pieceSize blk = (offset, offset + len)
42 where
43 offset = fromIntegral pieceSize * fromIntegral (blkPiece blk)
44 + fromIntegral (blkOffset blk)
45 len = fromIntegral (B.length (blkData blk))
46{-# INLINE blockRange #-}
47{-# SPECIALIZE blockRange :: Int -> Block -> (Int64, Int64) #-}
48
49ixRange :: (Num a, Integral a) => Int -> BlockIx -> (a, a)
50ixRange pieceSize ix = (offset, offset + len)
51 where
52 offset = fromIntegral pieceSize * fromIntegral (ixPiece ix)
53 + fromIntegral (ixOffset ix)
54 len = fromIntegral (ixLength ix)
55{-# INLINE ixRange #-}
56{-# SPECIALIZE ixRange :: Int -> BlockIx -> (Int64, Int64) #-}