forked from grandecola/bigqueue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharena.go
71 lines (59 loc) · 1.51 KB
/
arena.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
package bigqueue
import (
"os"
"syscall"
"github.com/grandecola/mmap"
)
const (
cFilePerm = 0744
)
// arena is an abstraction for a memory mapped file of a given size
type arena struct {
mmap.File
// TODO: this flag is being touched from a lot of places, we need to encapsulate it's usage better
dirty bool
}
// newArena returns pointer to an arena. It takes a file location and mmaps it.
// If file location does not exist, it creates file of given size.
func newArena(file string, size int) (*arena, error) {
fd, err := openOrCreateFile(file, size)
if err != nil {
return nil, err
}
m, err := mmap.NewSharedFileMmap(fd, 0, size, syscall.PROT_READ|syscall.PROT_WRITE)
if err != nil {
return nil, err
}
// We can close the file descriptor here
if err := fd.Close(); err != nil {
return nil, err
}
return &arena{
File: m,
}, nil
}
// openOrCreateFile opens the file if it exists,
// otherwise creates a new file of given size
func openOrCreateFile(file string, size int) (*os.File, error) {
if _, errExist := os.Stat(file); errExist == nil {
// open file
fd, err := os.OpenFile(file, os.O_RDWR, cFilePerm)
if err != nil {
return nil, err
}
return fd, nil
} else if os.IsNotExist(errExist) {
// create an empty file
fd, err := os.OpenFile(file, os.O_CREATE|os.O_RDWR, cFilePerm)
if err != nil {
return nil, err
}
// truncate the file to required size
if err := os.Truncate(file, int64(size)); err != nil {
return nil, err
}
return fd, nil
} else {
return nil, errExist
}
}