8 "github.com/edsrzf/mmap-go"
10 "github.com/anacrolix/torrent/segments"
13 type MMapSpan struct {
16 segmentLocater segments.Index
19 func (ms *MMapSpan) Append(mMap mmap.MMap) {
20 ms.mMaps = append(ms.mMaps, mMap)
23 func (ms *MMapSpan) Flush() (errs []error) {
26 for _, mMap := range ms.mMaps {
29 errs = append(errs, err)
35 func (ms *MMapSpan) Close() (errs []error) {
38 for _, mMap := range ms.mMaps {
41 errs = append(errs, err)
44 // This is for issue 211.
50 func (me *MMapSpan) InitIndex() {
52 me.segmentLocater = segments.NewIndex(func() (segments.Length, bool) {
53 if i == len(me.mMaps) {
56 l := int64(len(me.mMaps[i]))
60 // log.Printf("made mmapspan index: %v", me.segmentLocater)
63 func (ms *MMapSpan) ReadAt(p []byte, off int64) (n int, err error) {
64 // log.Printf("reading %v bytes at %v", len(p), off)
67 n = ms.locateCopy(func(a, b []byte) (_, _ []byte) { return a, b }, p, off)
74 func copyBytes(dst, src []byte) int {
78 func (ms *MMapSpan) locateCopy(copyArgs func(remainingArgument, mmapped []byte) (dst, src []byte), p []byte, off int64) (n int) {
79 ms.segmentLocater.Locate(segments.Extent{off, int64(len(p))}, func(i int, e segments.Extent) bool {
80 mMapBytes := ms.mMaps[i][e.Start:]
81 // log.Printf("got segment %v: %v, copying %v, %v", i, e, len(p), len(mMapBytes))
82 _n := copyBytes(copyArgs(p, mMapBytes))
86 if segments.Int(_n) != e.Length {
87 panic(fmt.Sprintf("did %d bytes, expected to do %d", _n, e.Length))
94 func (ms *MMapSpan) WriteAt(p []byte, off int64) (n int, err error) {
95 // log.Printf("writing %v bytes at %v", len(p), off)
98 n = ms.locateCopy(func(a, b []byte) (_, _ []byte) { return b, a }, p, off)
100 err = io.ErrShortWrite