blob: bb6c5d2eabfb30524dcdb73ac058c4919f1be2a5 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
-- |
-- Copyright : (c) Sam Truzjan 2013
-- License : BSD3
-- Maintainer : pxqr.sta@gmail.com
-- Stability : experimental
-- Portability : portable
--
-- This module implements mapping from single continious piece space
-- to file storage. Storage can be used in two modes:
--
-- * As in memory storage - in this case we don't touch filesystem.
--
-- * As ordinary mmaped file storage - when we need to store
-- data in the filesystem.
--
{-# LANGUAGE RecordWildCards #-}
module System.Torrent.Storage
( Storage
-- * Construction
, Mode (..)
, def
, open
, close
-- * Modification
, writePiece
, readPiece
, unsafeReadPiece
) where
import Control.Applicative
import Data.ByteString.Lazy as BL
import Data.Torrent.Layout
import Data.Torrent.Piece
import System.Torrent.FileMap
-- TODO validation
data Storage = Storage
{ pieceLen :: {-# UNPACK #-} !PieceSize
, fileMap :: {-# UNPACK #-} !FileMap
}
-- ResourceT ?
open :: Mode -> PieceSize -> FileLayout FileSize -> IO Storage
open mode s l = Storage s <$> mmapFiles mode l
close :: Storage -> IO ()
close Storage {..} = unmapFiles fileMap
writePiece :: Piece BL.ByteString -> Storage -> IO ()
writePiece Piece {..} Storage {..} = do
writeBytes (fromIntegral (pieceIndex * pieceLen)) pieceData fileMap
readPiece :: PieceIx -> Storage -> IO (Piece BL.ByteString)
readPiece pix Storage {..} = do
bs <- readBytes (fromIntegral (pix * pieceLen))
(fromIntegral pieceLen) fileMap
return $ Piece pix bs
unsafeReadPiece :: PieceIx -> Storage -> IO (Piece BL.ByteString)
unsafeReadPiece pix Storage {..} = return $ Piece pix lbs
where
lbs = unsafeReadBytes (fromIntegral (pix * pieceLen))
(fromIntegral pieceLen) fileMap
|