nameWithoutNamlen.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // +build nacl linux js solaris
  2. package godirwalk
  3. import (
  4. "bytes"
  5. "reflect"
  6. "syscall"
  7. "unsafe"
  8. )
  9. // nameOffset is a compile time constant
  10. const nameOffset = int(unsafe.Offsetof(syscall.Dirent{}.Name))
  11. func nameFromDirent(de *syscall.Dirent) (name []byte) {
  12. // Because this GOOS' syscall.Dirent does not provide a field that specifies
  13. // the name length, this function must first calculate the max possible name
  14. // length, and then search for the NULL byte.
  15. ml := int(de.Reclen) - nameOffset
  16. // Convert syscall.Dirent.Name, which is array of int8, to []byte, by
  17. // overwriting Cap, Len, and Data slice header fields to the max possible
  18. // name length computed above, and finding the terminating NULL 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. if index := bytes.IndexByte(name, 0); index >= 0 {
  24. // Found NULL byte; set slice's cap and len accordingly.
  25. sh.Cap = index
  26. sh.Len = index
  27. return
  28. }
  29. // NOTE: This branch is not expected, but included for defensive
  30. // programming, and provides a hard stop on the name based on the structure
  31. // field array size.
  32. sh.Cap = len(de.Name)
  33. sh.Len = sh.Cap
  34. return
  35. }