-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmmap.go
More file actions
105 lines (83 loc) · 2.07 KB
/
mmap.go
File metadata and controls
105 lines (83 loc) · 2.07 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package gobigqueue
import (
"os"
"sync"
"syscall"
"github.com/go-errors/errors"
"github.com/jaeyo/gobigqueue/utils"
)
type MmapWrapper struct {
mapFile *os.File
mmap []byte
writeLock *sync.Mutex
}
func (mmap *MmapWrapper) Set(data []byte, pos int) {
mmap.writeLock.Lock()
defer mmap.writeLock.Unlock()
endPos := pos + len(data)
copy(mmap.mmap[pos:endPos], data[:])
}
func (mmap *MmapWrapper) Get(pos, length int) []byte {
endPos := pos + length
data := make([]byte, length)
copy(data[:], mmap.mmap[pos:endPos])
return data
}
func (mmap *MmapWrapper) Close() error {
err := syscall.Munmap(mmap.mmap)
if err != nil {
return errors.Errorf(err.Error())
}
err = mmap.mapFile.Close()
if err != nil {
return errors.Errorf(err.Error())
}
return nil
}
func newMapFile(filename string, length int64) (*os.File, error) {
mapFile, err := os.Create(filename)
if err != nil {
return nil, errors.Errorf(err.Error())
}
_, err = mapFile.Seek(length-1, 0)
if err != nil {
return nil, errors.Errorf(err.Error())
}
_, err = mapFile.Write([]byte(" "))
if err != nil {
return nil, errors.Errorf(err.Error())
}
return mapFile, nil
}
func mmap(mapFile *os.File, length int) ([]byte, error) {
mmap, err := syscall.Mmap(int(mapFile.Fd()), 0, length, syscall.PROT_READ|syscall.PROT_WRITE, syscall.MAP_SHARED)
if err != nil {
return nil, errors.Errorf(err.Error())
}
return mmap, nil
}
func NewMmap(filename string, length int) (*MmapWrapper, bool, error) {
mapFile, isNew, err := func() (*os.File, bool, error) {
if exists, _ := utils.Exists(filename); exists == false {
mapFile, err := newMapFile(filename, int64(length))
if err != nil {
return nil, false, err
}
return mapFile, true, nil
}
mapFile, err := os.Open(filename)
if err != nil {
return nil, true, errors.Errorf(err.Error())
}
return mapFile, false, nil
}()
if err != nil {
return nil, isNew, err
}
mmap, err := mmap(mapFile, length)
if err != nil {
return nil, isNew, err
}
writeLock := &sync.Mutex{}
return &MmapWrapper{mapFile, mmap, writeLock}, isNew, nil
}