9 "github.com/anacrolix/missinggo"
10 "github.com/edsrzf/mmap-go"
12 "github.com/anacrolix/torrent/metainfo"
13 "github.com/anacrolix/torrent/mmap_span"
16 type mmapStorage struct {
20 func NewMMap(baseDir string) ClientImpl {
26 func (s *mmapStorage) OpenTorrent(info *metainfo.Info, infoHash metainfo.Hash) (t TorrentImpl, err error) {
27 span, err := mMapTorrent(info, s.baseDir)
28 t = &mmapTorrentStorage{
30 pc: pieceCompletionForDir(s.baseDir),
35 type mmapTorrentStorage struct {
36 span mmap_span.MMapSpan
40 func (ts *mmapTorrentStorage) Piece(p metainfo.Piece) PieceImpl {
41 return mmapStoragePiece{
44 ReaderAt: io.NewSectionReader(ts.span, p.Offset(), p.Length()),
45 WriterAt: missinggo.NewSectionWriter(ts.span, p.Offset(), p.Length()),
49 func (ts *mmapTorrentStorage) Close() error {
51 return ts.span.Close()
54 type mmapStoragePiece struct {
62 func (me mmapStoragePiece) pieceKey() metainfo.PieceKey {
63 return metainfo.PieceKey{me.ih, me.p.Index()}
66 func (sp mmapStoragePiece) GetIsComplete() (ret bool) {
67 ret, _ = sp.pc.Get(sp.pieceKey())
71 func (sp mmapStoragePiece) MarkComplete() error {
72 sp.pc.Set(sp.pieceKey(), true)
76 func (sp mmapStoragePiece) MarkNotComplete() error {
77 sp.pc.Set(sp.pieceKey(), false)
81 func mMapTorrent(md *metainfo.Info, location string) (mms mmap_span.MMapSpan, err error) {
87 for _, miFile := range md.UpvertedFiles() {
88 fileName := filepath.Join(append([]string{location, md.Name}, miFile.Path...)...)
89 err = os.MkdirAll(filepath.Dir(fileName), 0777)
91 err = fmt.Errorf("error creating data directory %q: %s", filepath.Dir(fileName), err)
95 file, err = os.OpenFile(fileName, os.O_CREATE|os.O_RDWR, 0666)
102 fi, err = file.Stat()
106 if fi.Size() < miFile.Length {
107 err = file.Truncate(miFile.Length)
112 if miFile.Length == 0 {
113 // Can't mmap() regions with length 0.
117 mMap, err = mmap.MapRegion(file,
118 int(miFile.Length), // Probably not great on <64 bit systems.
121 err = fmt.Errorf("error mapping file %q, length %d: %s", file.Name(), miFile.Length, err)
124 if int64(len(mMap)) != miFile.Length {
125 panic("mmap has wrong length")