summaryrefslogtreecommitdiff
path: root/src/pkg/os/dir_darwin.go
blob: 861bcef27d46f53ef8e3adac6e1d6eae94d15817 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package os

import (
	"syscall"
	"unsafe"
)

const (
	blockSize = 4096 // TODO(r): use statfs
)

// Readdirnames reads the contents of the directory associated with file and
// returns an array of up to count names, in directory order.  Subsequent
// calls on the same file will yield further names.
// A negative count means to read until EOF.
// Readdirnames returns the array and an Error, if any.
func (file *File) Readdirnames(count int) (names []string, err Error) {
	// If this file has no dirinfo, create one.
	if file.dirinfo == nil {
		file.dirinfo = new(dirInfo)
		// The buffer must be at least a block long.
		// TODO(r): use fstatfs to find fs block size.
		file.dirinfo.buf = make([]byte, blockSize)
	}
	d := file.dirinfo
	size := count
	if size < 0 {
		size = 100
	}
	names = make([]string, 0, size) // Empty with room to grow.
	for count != 0 {
		// Refill the buffer if necessary
		if d.bufp >= d.nbuf {
			var errno int
			d.bufp = 0
			// Final argument is (basep *uintptr) and the syscall doesn't take nil.
			d.nbuf, errno = syscall.Getdirentries(file.fd, d.buf, new(uintptr))
			if errno != 0 {
				d.nbuf = 0
				return names, NewSyscallError("getdirentries", errno)
			}
			if d.nbuf <= 0 {
				break // EOF
			}
		}
		// Drain the buffer
		for count != 0 && d.bufp < d.nbuf {
			dirent := (*syscall.Dirent)(unsafe.Pointer(&d.buf[d.bufp]))
			if dirent.Reclen == 0 {
				d.bufp = d.nbuf
				break
			}
			d.bufp += int(dirent.Reclen)
			if dirent.Ino == 0 { // File absent in directory.
				continue
			}
			bytes := (*[10000]byte)(unsafe.Pointer(&dirent.Name[0]))
			var name = string(bytes[0:dirent.Namlen])
			if name == "." || name == ".." { // Useless names
				continue
			}
			count--
			names = append(names, name)
		}
	}
	return names, nil
}