mmap_darwin.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. * Copyright 2019 Dgraph Labs, Inc. and Contributors
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package z
  17. import (
  18. "os"
  19. "syscall"
  20. "unsafe"
  21. "golang.org/x/sys/unix"
  22. )
  23. // Mmap uses the mmap system call to memory-map a file. If writable is true,
  24. // memory protection of the pages is set so that they may be written to as well.
  25. func mmap(fd *os.File, writable bool, size int64) ([]byte, error) {
  26. mtype := unix.PROT_READ
  27. if writable {
  28. mtype |= unix.PROT_WRITE
  29. }
  30. return unix.Mmap(int(fd.Fd()), 0, int(size), mtype, unix.MAP_SHARED)
  31. }
  32. // Munmap unmaps a previously mapped slice.
  33. func munmap(b []byte) error {
  34. return unix.Munmap(b)
  35. }
  36. // This is required because the unix package does not support the madvise system call on OS X.
  37. func madvise(b []byte, readahead bool) error {
  38. advice := unix.MADV_NORMAL
  39. if !readahead {
  40. advice = unix.MADV_RANDOM
  41. }
  42. _, _, e1 := syscall.Syscall(syscall.SYS_MADVISE, uintptr(unsafe.Pointer(&b[0])),
  43. uintptr(len(b)), uintptr(advice))
  44. if e1 != 0 {
  45. return e1
  46. }
  47. return nil
  48. }
  49. func msync(b []byte) error {
  50. return unix.Msync(b, unix.MS_SYNC)
  51. }