mmap_unix.go raw
1 //go:build !windows && !darwin && !plan9 && !linux && !wasip1 && !js
2 // +build !windows,!darwin,!plan9,!linux,!wasip1,!js
3
4 /*
5 * SPDX-FileCopyrightText: © Hypermode Inc. <hello@hypermode.com>
6 * SPDX-License-Identifier: Apache-2.0
7 */
8
9 package z
10
11 import (
12 "os"
13
14 "golang.org/x/sys/unix"
15 )
16
17 // Mmap uses the mmap system call to memory-map a file. If writable is true,
18 // memory protection of the pages is set so that they may be written to as well.
19 func mmap(fd *os.File, writable bool, size int64) ([]byte, error) {
20 mtype := unix.PROT_READ
21 if writable {
22 mtype |= unix.PROT_WRITE
23 }
24 return unix.Mmap(int(fd.Fd()), 0, int(size), mtype, unix.MAP_SHARED)
25 }
26
27 // Munmap unmaps a previously mapped slice.
28 func munmap(b []byte) error {
29 return unix.Munmap(b)
30 }
31
32 // Madvise uses the madvise system call to give advise about the use of memory
33 // when using a slice that is memory-mapped to a file. Set the readahead flag to
34 // false if page references are expected in random order.
35 func madvise(b []byte, readahead bool) error {
36 flags := unix.MADV_NORMAL
37 if !readahead {
38 flags = unix.MADV_RANDOM
39 }
40 return unix.Madvise(b, flags)
41 }
42
43 func msync(b []byte) error {
44 return unix.Msync(b, unix.MS_SYNC)
45 }
46