fork of https://github.com/sourcegraph/zoekt
1// Copyright 2016 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//go:build linux || darwin || freebsd
16
17package index
18
19import (
20 "fmt"
21 "log"
22 "math"
23 "os"
24
25 "golang.org/x/sys/unix"
26)
27
28type mmapedIndexFile struct {
29 name string
30 size uint32
31 data []byte
32}
33
34func (f *mmapedIndexFile) Read(off, sz uint32) ([]byte, error) {
35 if off > off+sz || off+sz > uint32(len(f.data)) {
36 return nil, fmt.Errorf("out of bounds: %d, len %d, name %s", off+sz, len(f.data), f.name)
37 }
38 return f.data[off : off+sz], nil
39}
40
41func (f *mmapedIndexFile) Name() string {
42 return f.name
43}
44
45func (f *mmapedIndexFile) Size() (uint32, error) {
46 return f.size, nil
47}
48
49func (f *mmapedIndexFile) Close() {
50 if err := unix.Munmap(f.data); err != nil {
51 log.Printf("WARN failed to Munmap %s: %v", f.name, err)
52 }
53}
54
55// NewIndexFile returns a new index file. The index file takes
56// ownership of the passed in file, and may close it.
57func NewIndexFile(f *os.File) (IndexFile, error) {
58 defer f.Close()
59
60 fi, err := f.Stat()
61 if err != nil {
62 return nil, err
63 }
64
65 sz := fi.Size()
66 if sz >= math.MaxUint32 {
67 return nil, fmt.Errorf("file %s too large: %d", f.Name(), sz)
68 }
69 r := &mmapedIndexFile{
70 name: f.Name(),
71 size: uint32(sz),
72 }
73
74 rounded := (r.size + 4095) &^ 4095
75 r.data, err = unix.Mmap(int(f.Fd()), 0, int(rounded), unix.PROT_READ, unix.MAP_SHARED)
76 if err != nil {
77 return nil, err
78 }
79
80 return r, err
81}