From 08bb327005c2f0dc517d0a74cf29e9f7f9b08e21 Mon Sep 17 00:00:00 2001 From: Sam T Date: Sat, 20 Apr 2013 23:50:45 +0400 Subject: + Add some block functions. --- src/Network/Torrent/PeerWire/Block.hs | 41 ++++++++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) (limited to 'src/Network') 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 @@ module Network.Torrent.PeerWire.Block ( BlockIx(..), Block(..) + , defaultBlockSize + , blockRange, ixRange, pieceIx + , isPiece ) where -import Data.ByteString (ByteString) +import Data.ByteString (ByteString) +import qualified Data.ByteString as B +import Data.Int + data BlockIx = BlockIx { ixPiece :: {-# UNPACK #-} !Int -- ^ Zero-based piece index. @@ -15,3 +21,36 @@ data Block = Block { , blkOffset :: Int -- ^ Zero-based byte offset within the piece. , blkData :: ByteString -- ^ Payload. } deriving (Show, Eq) + + +-- | Widely used semi-official block size. +defaultBlockSize :: Int +defaultBlockSize = 16 * 1024 + + +isPiece :: Int -> Block -> Bool +isPiece pieceSize (Block i offset bs) = + offset == 0 && B.length bs == pieceSize && i >= 0 +{-# INLINE isPiece #-} + +pieceIx :: Int -> Int -> BlockIx +pieceIx i = BlockIx i 0 +{-# INLINE pieceIx #-} + +blockRange :: (Num a, Integral a) => Int -> Block -> (a, a) +blockRange pieceSize blk = (offset, offset + len) + where + offset = fromIntegral pieceSize * fromIntegral (blkPiece blk) + + fromIntegral (blkOffset blk) + len = fromIntegral (B.length (blkData blk)) +{-# INLINE blockRange #-} +{-# SPECIALIZE blockRange :: Int -> Block -> (Int64, Int64) #-} + +ixRange :: (Num a, Integral a) => Int -> BlockIx -> (a, a) +ixRange pieceSize ix = (offset, offset + len) + where + offset = fromIntegral pieceSize * fromIntegral (ixPiece ix) + + fromIntegral (ixOffset ix) + len = fromIntegral (ixLength ix) +{-# INLINE ixRange #-} +{-# SPECIALIZE ixRange :: Int -> BlockIx -> (Int64, Int64) #-} -- cgit v1.2.3