1//  Copyright (c) 2017 Couchbase, Inc.
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// +build !nommap
16
17package vellum
18
19import (
20	"os"
21
22	mmap "github.com/edsrzf/mmap-go"
23)
24
25type mmapWrapper struct {
26	f  *os.File
27	mm mmap.MMap
28}
29
30func (m *mmapWrapper) Close() (err error) {
31	if m.mm != nil {
32		err = m.mm.Unmap()
33	}
34	// try to close file even if unmap failed
35	if m.f != nil {
36		err2 := m.f.Close()
37		if err == nil {
38			// try to return first error
39			err = err2
40		}
41	}
42	return
43}
44
45func open(path string) (*FST, error) {
46	f, err := os.Open(path)
47	if err != nil {
48		return nil, err
49	}
50	mm, err := mmap.Map(f, mmap.RDONLY, 0)
51	if err != nil {
52		// mmap failed, try to close the file
53		_ = f.Close()
54		return nil, err
55	}
56	return new(mm, &mmapWrapper{
57		f:  f,
58		mm: mm,
59	})
60}
61