withNamlen.go 823 B

123456789101112131415161718192021222324252627282930
  1. // +build darwin dragonfly freebsd netbsd openbsd
  2. package godirwalk
  3. import (
  4. "reflect"
  5. "syscall"
  6. "unsafe"
  7. )
  8. func nameFromDirent(de *syscall.Dirent) []byte {
  9. // Because this GOOS' syscall.Dirent provides a Namlen field that says how
  10. // long the name is, this function does not need to search for the NULL
  11. // byte.
  12. ml := int(de.Namlen)
  13. // Convert syscall.Dirent.Name, which is array of int8, to []byte, by
  14. // overwriting Cap, Len, and Data slice header fields to values from
  15. // syscall.Dirent fields. Setting the Cap, Len, and Data field values for
  16. // the slice header modifies what the slice header points to, and in this
  17. // case, the name buffer.
  18. var name []byte
  19. sh := (*reflect.SliceHeader)(unsafe.Pointer(&name))
  20. sh.Cap = ml
  21. sh.Len = ml
  22. sh.Data = uintptr(unsafe.Pointer(&de.Name[0]))
  23. return name
  24. }