-
Notifications
You must be signed in to change notification settings - Fork 8
/
bytes_file.go
59 lines (52 loc) · 1.26 KB
/
bytes_file.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
//go:build linux && amd64
// +build linux,amd64
package lru
import (
"fmt"
"os"
"syscall"
)
type bytesfile struct {
location string
file *os.File
size int
}
func (m *bytesfile) close() error {
return m.file.Close()
}
func (m *bytesfile) open() error {
var openingFlag = os.O_RDWR
if _, err := os.Stat(m.location); os.IsNotExist(err) {
openingFlag = openingFlag | os.O_CREATE
}
var err error
if m.file, err = os.OpenFile(m.location, openingFlag, 0644); err != nil {
return fmt.Errorf("failed to create file %v: %w", m.location, err)
}
return m.allocate()
}
func (m *bytesfile) assign(offset int64, target *[]byte) error {
buffer, err := syscall.Mmap(int(m.file.Fd()), offset, m.size, syscall.PROT_READ|syscall.PROT_WRITE, syscall.MAP_SHARED)
if err != nil {
return fmt.Errorf("failed to map memory %v: %w", m.location, err)
}
*target = buffer
return nil
}
func (m *bytesfile) allocate() error {
info, err := os.Stat(m.location)
if err != nil {
return err
}
if info.Size() < int64(m.size) {
_, err := m.file.Seek(int64(m.size-1), 0)
if err != nil {
return fmt.Errorf("Failed to seek file %v", err)
}
_, err = m.file.Write([]byte{0})
if err != nil {
return fmt.Errorf("failed to resize %v: %w", m.location, err)
}
}
return nil
}