mmap_darwin.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /*
  2. * SPDX-FileCopyrightText: © Hypermode Inc. <hello@hypermode.com>
  3. * SPDX-License-Identifier: Apache-2.0
  4. */
  5. package z
  6. import (
  7. "os"
  8. "syscall"
  9. "unsafe"
  10. "golang.org/x/sys/unix"
  11. )
  12. // Mmap uses the mmap system call to memory-map a file. If writable is true,
  13. // memory protection of the pages is set so that they may be written to as well.
  14. func mmap(fd *os.File, writable bool, size int64) ([]byte, error) {
  15. mtype := unix.PROT_READ
  16. if writable {
  17. mtype |= unix.PROT_WRITE
  18. }
  19. return unix.Mmap(int(fd.Fd()), 0, int(size), mtype, unix.MAP_SHARED)
  20. }
  21. // Munmap unmaps a previously mapped slice.
  22. func munmap(b []byte) error {
  23. return unix.Munmap(b)
  24. }
  25. // This is required because the unix package does not support the madvise system call on OS X.
  26. func madvise(b []byte, readahead bool) error {
  27. advice := unix.MADV_NORMAL
  28. if !readahead {
  29. advice = unix.MADV_RANDOM
  30. }
  31. _, _, e1 := syscall.Syscall(syscall.SYS_MADVISE, uintptr(unsafe.Pointer(&b[0])),
  32. uintptr(len(b)), uintptr(advice))
  33. if e1 != 0 {
  34. return e1
  35. }
  36. return nil
  37. }
  38. func msync(b []byte) error {
  39. return unix.Msync(b, unix.MS_SYNC)
  40. }