-
Notifications
You must be signed in to change notification settings - Fork 1
/
mmap.go
47 lines (43 loc) · 933 Bytes
/
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
package main
import (
"fmt"
"os"
"syscall"
)
// Open will mmap a file to a byte slice of data.
func Open(path string, writable bool) (data []byte, err error) {
flag, prot := os.O_RDONLY, syscall.PROT_READ
if writable {
flag, prot = os.O_RDWR, syscall.PROT_READ|syscall.PROT_WRITE
}
f, err := os.OpenFile(path, flag, 0666)
if err != nil {
return nil, err
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
return nil, err
}
if fi.Size() > 0 {
return syscall.Mmap(int(f.Fd()), 0, int(fi.Size()),
prot, syscall.MAP_SHARED)
}
return nil, nil
}
// Close releases the data. Don't read the data after running this operation
// otherwise your f*cked.
func Close(data []byte) error {
if len(data) > 0 {
return syscall.Munmap(data)
}
return nil
}
func main() {
data, err := Open("/Users/maiyang/Downloads/paul_bill3.jpg", true)
if err != nil {
panic(err)
}
fmt.Println(string(data))
Close(data)
}