influxdb/pkg/mmap/mmap_windows.go

57 lines
1.0 KiB
Go
Raw Normal View History

2016-10-03 15:08:43 +00:00
package mmap
import (
"os"
"syscall"
"unsafe"
)
// Map memory-maps a file.
2017-09-14 15:41:58 +00:00
func Map(path string, sz int64) ([]byte, error) {
2018-06-29 16:08:54 +00:00
fi, err := os.Stat(path)
2016-10-03 15:08:43 +00:00
if err != nil {
return nil, err
}
2018-06-29 16:08:54 +00:00
// Truncate file to size if too small.
if fi.Size() < sz {
if err := os.Truncate(path, sz); err != nil {
return nil, err
}
} else {
sz = fi.Size()
2017-09-14 15:41:58 +00:00
}
2018-06-29 16:08:54 +00:00
if sz == 0 {
2016-10-03 15:08:43 +00:00
return nil, nil
}
2018-06-29 16:08:54 +00:00
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
2017-09-14 15:41:58 +00:00
lo, hi := uint32(sz), uint32(sz>>32)
2016-10-03 15:08:43 +00:00
fmap, err := syscall.CreateFileMapping(syscall.Handle(f.Fd()), nil, syscall.PAGE_READONLY, hi, lo, nil)
if err != nil {
return nil, err
}
defer syscall.CloseHandle(fmap)
2017-09-14 15:41:58 +00:00
ptr, err := syscall.MapViewOfFile(fmap, syscall.FILE_MAP_READ, 0, 0, uintptr(sz))
2016-10-03 15:08:43 +00:00
if err != nil {
return nil, err
}
2017-09-14 15:41:58 +00:00
data := (*[1 << 30]byte)(unsafe.Pointer(ptr))[:sz]
2016-10-03 15:08:43 +00:00
return data, nil
}
// Unmap closes the memory-map.
func Unmap(data []byte) error {
if data == nil {
return nil
}
return syscall.UnmapViewOfFile(uintptr(unsafe.Pointer(&data[0])))
}