2014-04-08 16:36:05 +00:00
|
|
|
package mmap_span
|
2013-09-26 03:42:24 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
2016-03-28 11:40:29 +00:00
|
|
|
"log"
|
2014-04-08 09:39:34 +00:00
|
|
|
|
2015-12-22 16:50:34 +00:00
|
|
|
"github.com/edsrzf/mmap-go"
|
2013-09-26 03:42:24 +00:00
|
|
|
)
|
|
|
|
|
2014-04-08 16:36:05 +00:00
|
|
|
type segment struct {
|
2015-12-22 16:50:34 +00:00
|
|
|
*mmap.MMap
|
2013-09-26 03:42:24 +00:00
|
|
|
}
|
|
|
|
|
2016-04-19 04:11:11 +00:00
|
|
|
func (s segment) Size() int64 {
|
|
|
|
return int64(len(*s.MMap))
|
2013-09-26 03:42:24 +00:00
|
|
|
}
|
|
|
|
|
2014-12-05 06:54:55 +00:00
|
|
|
type MMapSpan struct {
|
|
|
|
span
|
|
|
|
}
|
2013-09-26 03:42:24 +00:00
|
|
|
|
2016-04-19 04:11:11 +00:00
|
|
|
func (ms *MMapSpan) Append(mmap mmap.MMap) {
|
|
|
|
ms.span = append(ms.span, segment{&mmap})
|
2013-09-26 03:42:24 +00:00
|
|
|
}
|
|
|
|
|
2016-04-19 04:11:11 +00:00
|
|
|
func (ms MMapSpan) Close() error {
|
|
|
|
for _, mMap := range ms.span {
|
2016-03-28 11:40:29 +00:00
|
|
|
err := mMap.(segment).Unmap()
|
|
|
|
if err != nil {
|
|
|
|
log.Print(err)
|
|
|
|
}
|
2013-09-26 09:49:15 +00:00
|
|
|
}
|
2016-03-28 11:40:29 +00:00
|
|
|
return nil
|
2013-09-26 09:49:15 +00:00
|
|
|
}
|
|
|
|
|
2016-04-19 04:11:11 +00:00
|
|
|
func (ms MMapSpan) Size() (ret int64) {
|
|
|
|
for _, seg := range ms.span {
|
2014-04-08 16:36:05 +00:00
|
|
|
ret += seg.Size()
|
2013-09-26 03:42:24 +00:00
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2016-04-19 04:11:11 +00:00
|
|
|
func (ms MMapSpan) ReadAt(p []byte, off int64) (n int, err error) {
|
|
|
|
ms.ApplyTo(off, func(intervalOffset int64, interval sizer) (stop bool) {
|
2015-12-22 16:50:34 +00:00
|
|
|
_n := copy(p, (*interval.(segment).MMap)[intervalOffset:])
|
2013-09-26 03:42:24 +00:00
|
|
|
p = p[_n:]
|
|
|
|
n += _n
|
|
|
|
return len(p) == 0
|
|
|
|
})
|
|
|
|
if len(p) != 0 {
|
|
|
|
err = io.EOF
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2016-04-19 04:11:11 +00:00
|
|
|
func (ms MMapSpan) WriteAt(p []byte, off int64) (n int, err error) {
|
|
|
|
ms.ApplyTo(off, func(iOff int64, i sizer) (stop bool) {
|
2014-04-08 16:36:05 +00:00
|
|
|
mMap := i.(segment)
|
2015-12-22 16:50:34 +00:00
|
|
|
_n := copy((*mMap.MMap)[iOff:], p)
|
2013-10-20 14:07:01 +00:00
|
|
|
// err = mMap.Sync(gommap.MS_ASYNC)
|
|
|
|
// if err != nil {
|
|
|
|
// return true
|
|
|
|
// }
|
2013-09-26 03:42:24 +00:00
|
|
|
p = p[_n:]
|
|
|
|
n += _n
|
|
|
|
return len(p) == 0
|
|
|
|
})
|
2013-10-20 14:07:01 +00:00
|
|
|
if err != nil && len(p) != 0 {
|
2013-10-02 09:54:23 +00:00
|
|
|
err = io.ErrShortWrite
|
2013-09-26 03:42:24 +00:00
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|