forked from nutsdb/nutsdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrwmanger_mmap.go
75 lines (60 loc) · 1.88 KB
/
rwmanger_mmap.go
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
68
69
70
71
72
73
74
75
package nutsdb
import (
"errors"
"os"
"github.com/xujiajun/mmap-go"
)
// MMapRWManager represents the RWManager which using mmap.
type MMapRWManager struct {
m mmap.MMap
}
var (
// ErrUnmappedMemory is returned when a function is called on unmapped memory
ErrUnmappedMemory = errors.New("unmapped memory")
// ErrIndexOutOfBound is returned when given offset out of mapped region
ErrIndexOutOfBound = errors.New("offset out of mapped region")
)
// NewMMapRWManager returns a newly initialized MMapRWManager.
func NewMMapRWManager(path string, capacity int64) (*MMapRWManager, error) {
f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0644)
if err != nil {
return nil, err
}
err = Truncate(path, capacity, f)
if err != nil {
return nil, err
}
m, err := mmap.Map(f, mmap.RDWR, 0)
if err != nil {
return nil, err
}
return &MMapRWManager{m: m}, nil
}
// WriteAt copies data to mapped region from the b slice starting at
// given off and returns number of bytes copied to the mapped region.
func (mm *MMapRWManager) WriteAt(b []byte, off int64) (n int, err error) {
if mm.m == nil {
return 0, ErrUnmappedMemory
} else if off >= int64(len(mm.m)) || off < 0 {
return 0, ErrIndexOutOfBound
}
return copy(mm.m[off:], b), nil
}
// ReadAt copies data to b slice from mapped region starting at
// given off and returns number of bytes copied to the b slice.
func (mm *MMapRWManager) ReadAt(b []byte, off int64) (n int, err error) {
if mm.m == nil {
return 0, ErrUnmappedMemory
} else if off >= int64(len(mm.m)) || off < 0 {
return 0, ErrIndexOutOfBound
}
return copy(b, mm.m[off:]), nil
}
// Sync synchronizes the mapping's contents to the file's contents on disk.
func (mm *MMapRWManager) Sync() (err error) {
return mm.m.Flush()
}
//Close deletes the memory mapped region, flushes any remaining changes
func (mm *MMapRWManager) Close() (err error) {
return mm.m.Unmap()
}