withoutNamlen.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. // +build nacl linux solaris
  2. package godirwalk
  3. import (
  4. "bytes"
  5. "reflect"
  6. "syscall"
  7. "unsafe"
  8. )
  9. func nameFromDirent(de *syscall.Dirent) []byte {
  10. // Because this GOOS' syscall.Dirent does not provide a field that specifies
  11. // the name length, this function must first calculate the max possible name
  12. // length, and then search for the NULL byte.
  13. ml := int(uint64(de.Reclen) - uint64(unsafe.Offsetof(syscall.Dirent{}.Name)))
  14. // Convert syscall.Dirent.Name, which is array of int8, to []byte, by
  15. // overwriting Cap, Len, and Data slice header fields to values from
  16. // syscall.Dirent fields. Setting the Cap, Len, and Data field values for
  17. // the slice header modifies what the slice header points to, and in this
  18. // case, the name buffer.
  19. var name []byte
  20. sh := (*reflect.SliceHeader)(unsafe.Pointer(&name))
  21. sh.Cap = ml
  22. sh.Len = ml
  23. sh.Data = uintptr(unsafe.Pointer(&de.Name[0]))
  24. if index := bytes.IndexByte(name, 0); index >= 0 {
  25. // Found NULL byte; set slice's cap and len accordingly.
  26. sh.Cap = index
  27. sh.Len = index
  28. }
  29. return name
  30. }