10 "github.com/anacrolix/missinggo"
11 "github.com/anacrolix/torrent/metainfo"
12 "github.com/anacrolix/torrent/mmap_span"
13 "github.com/edsrzf/mmap-go"
16 type mmapClientImpl struct {
21 func NewMMap(baseDir string) ClientImpl {
22 return NewMMapWithCompletion(baseDir, pieceCompletionForDir(baseDir))
25 func NewMMapWithCompletion(baseDir string, completion PieceCompletion) ClientImpl {
26 return &mmapClientImpl{
32 func (s *mmapClientImpl) OpenTorrent(info *metainfo.Info, infoHash metainfo.Hash) (t TorrentImpl, err error) {
33 span, err := mMapTorrent(info, s.baseDir)
34 t = &mmapTorrentStorage{
42 func (s *mmapClientImpl) Close() error {
46 type mmapTorrentStorage struct {
47 infoHash metainfo.Hash
48 span *mmap_span.MMapSpan
52 func (ts *mmapTorrentStorage) Piece(p metainfo.Piece) PieceImpl {
53 return mmapStoragePiece{
57 ReaderAt: io.NewSectionReader(ts.span, p.Offset(), p.Length()),
58 WriterAt: missinggo.NewSectionWriter(ts.span, p.Offset(), p.Length()),
62 func (ts *mmapTorrentStorage) Close() error {
64 return ts.span.Close()
67 type mmapStoragePiece struct {
75 func (me mmapStoragePiece) pieceKey() metainfo.PieceKey {
76 return metainfo.PieceKey{me.ih, me.p.Index()}
79 func (sp mmapStoragePiece) Completion() Completion {
80 c, _ := sp.pc.Get(sp.pieceKey())
84 func (sp mmapStoragePiece) MarkComplete() error {
85 sp.pc.Set(sp.pieceKey(), true)
89 func (sp mmapStoragePiece) MarkNotComplete() error {
90 sp.pc.Set(sp.pieceKey(), false)
94 func mMapTorrent(md *metainfo.Info, location string) (mms *mmap_span.MMapSpan, err error) {
95 mms = &mmap_span.MMapSpan{}
101 for _, miFile := range md.UpvertedFiles() {
102 fileName := filepath.Join(append([]string{location, md.Name}, miFile.Path...)...)
104 mm, err = mmapFile(fileName, miFile.Length)
106 err = fmt.Errorf("file %q: %s", miFile.DisplayPath(md), err)
116 func mmapFile(name string, size int64) (ret mmap.MMap, err error) {
117 dir := filepath.Dir(name)
118 err = os.MkdirAll(dir, 0777)
120 err = fmt.Errorf("making directory %q: %s", dir, err)
124 file, err = os.OpenFile(name, os.O_CREATE|os.O_RDWR, 0666)
130 fi, err = file.Stat()
134 if fi.Size() < size {
135 // I think this is necessary on HFS+. Maybe Linux will SIGBUS too if
136 // you overmap a file but I'm not sure.
137 err = file.Truncate(size)
143 // Can't mmap() regions with length 0.
147 if int64(intLen) != size {
148 err = errors.New("size too large for system")
151 ret, err = mmap.MapRegion(file, intLen, mmap.RDWR, 0, 0)
153 err = fmt.Errorf("error mapping region: %s", err)
156 if int64(len(ret)) != size {