/
mmap.go
62 lines (53 loc) · 1.16 KB
/
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
package memiavl
import (
"errors"
"os"
"github.com/ledgerwatch/erigon-lib/mmap"
)
// MmapFile manage the resources of a mmap-ed file
type MmapFile struct {
file *os.File
data []byte
// mmap handle for windows (this is used to close mmap)
handle *[mmap.MaxMapSize]byte
}
// Open openes the file and create the mmap.
// the mmap is created with flags: PROT_READ, MAP_SHARED, MADV_RANDOM.
func NewMmap(path string) (*MmapFile, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
data, handle, err := Mmap(file)
if err != nil {
_ = file.Close()
return nil, err
}
return &MmapFile{
file: file,
data: data,
handle: handle,
}, nil
}
// Close closes the file and mmap handles
func (m *MmapFile) Close() error {
var err error
if m.handle != nil {
err = mmap.Munmap(m.data, m.handle)
}
return errors.Join(err, m.file.Close())
}
// Data returns the mmap-ed buffer
func (m *MmapFile) Data() []byte {
return m.data
}
func Mmap(f *os.File) ([]byte, *[mmap.MaxMapSize]byte, error) {
fi, err := f.Stat()
if err != nil {
return nil, nil, err
}
if fi.Size() == 0 {
return nil, nil, nil
}
return mmap.Mmap(f, int(fi.Size()))
}