forked from canonical/go-gettext
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfilemapping.go
54 lines (45 loc) · 911 Bytes
/
filemapping.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
package gettext
import (
"fmt"
"io/fs"
"io/ioutil"
"runtime"
)
type fileMapping struct {
data []byte
isMapped bool
}
func (m *fileMapping) Close() error {
runtime.SetFinalizer(m, nil)
if !m.isMapped {
return nil
}
return m.closeMapping()
}
func openMapping(f fs.File) (*fileMapping, error) {
fi, err := f.Stat()
if err != nil {
return nil, err
}
m := new(fileMapping)
if fi.Mode().IsRegular() {
size := fi.Size()
if size == 0 {
return m, nil
}
if size < 0 {
return nil, fmt.Errorf("file %q has negative size", fi.Name())
}
if size != int64(int(size)) {
return nil, fmt.Errorf("file %q is too large", fi.Name())
}
if err := m.tryMap(f, size); err == nil {
runtime.SetFinalizer(m, (*fileMapping).Close)
return m, nil
}
}
// On mapping failure, fall back to reading the file into
// memory directly.
m.data, err = ioutil.ReadAll(f)
return m, err
}