File: binary_unix.go

package info (click to toggle)
golang-github-tdewolff-parse 2.8.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 844 kB
  • sloc: makefile: 2
file content (95 lines) | stat: -rw-r--r-- 2,129 bytes parent folder | download
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
//go:build unix

package parse

import (
	"errors"
	"fmt"
	"os"
	"runtime"
	"syscall"
)

type binaryReaderMmap struct {
	data []byte
	size int64
}

func newBinaryReaderMmap(filename string) (*binaryReaderMmap, error) {
	f, err := os.Open(filename)
	if err != nil {
		return nil, err
	}
	defer f.Close()

	info, err := f.Stat()
	if err != nil {
		return nil, err
	}

	size := info.Size()
	if size == 0 {
		// Treat (size == 0) as a special case, avoiding the syscall, since
		// "man 2 mmap" says "the length... must be greater than 0".
		//
		// As we do not call syscall.Mmap, there is no need to call
		// runtime.SetFinalizer to enforce a balancing syscall.Munmap.
		return &binaryReaderMmap{
			data: make([]byte, 0),
		}, nil
	} else if size < 0 {
		return nil, fmt.Errorf("mmap: file %s has negative size", filename)
	} else if size != int64(int(size)) {
		return nil, fmt.Errorf("mmap: file %s is too large", filename)
	}

	data, err := syscall.Mmap(int(f.Fd()), 0, int(size), syscall.PROT_READ, syscall.MAP_SHARED)
	if err != nil {
		return nil, err
	}
	r := &binaryReaderMmap{data, size}
	runtime.SetFinalizer(r, (*binaryReaderMmap).Close)
	return r, nil
}

// Close closes the reader.
func (r *binaryReaderMmap) Close() error {
	if r.data == nil {
		return nil
	} else if len(r.data) == 0 {
		r.data = nil
		return nil
	}
	data := r.data
	r.data = nil
	runtime.SetFinalizer(r, nil)
	return syscall.Munmap(data)
}

// Len returns the length of the underlying memory-mapped file.
func (r *binaryReaderMmap) Len() int64 {
	return r.size
}

func (r *binaryReaderMmap) Bytes(b []byte, n, off int64) ([]byte, error) {
	if r.data == nil {
		return nil, errors.New("mmap: closed")
	} else if off < 0 || n < 0 || int64(len(r.data)) < off || int64(len(r.data))-off < n {
		return nil, fmt.Errorf("mmap: invalid range %d--%d", off, off+n)
	}

	data := r.data[off : off+n : off+n]
	if b == nil {
		return data, nil
	}
	copy(b, data)
	return b, nil
}

func NewBinaryReaderMmap(filename string) (*BinaryReader, error) {
	f, err := newBinaryReaderMmap(filename)
	if err != nil {
		return nil, err
	}
	return NewBinaryReader(f), nil
}