-
Notifications
You must be signed in to change notification settings - Fork 0
/
readdircount_linux_amd64.go
62 lines (52 loc) · 1.19 KB
/
readdircount_linux_amd64.go
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
// +build linux,amd64
package fs
import (
"fmt"
"os"
"unsafe"
"syscall"
)
func countDirEntries(buf []byte, n int) int {
count := 0
buf = buf[:n]
for len(buf) > 0 {
// see man page getdents(2) for struct linux_dirent64
reclenOffset := unsafe.Offsetof(syscall.Dirent{}.Reclen)
reclen := *(*uint16)(unsafe.Pointer(&buf[reclenOffset]))
inoOffset := unsafe.Offsetof(syscall.Dirent{}.Ino)
ino := *(*uint64)(unsafe.Pointer(&buf[inoOffset]))
if int(reclen) > len(buf) {
return count
}
buf = buf[reclen:]
if ino == 0 {
continue
}
count++
}
return count
}
// ReadDirCount is similar to ReadDirNames() and then counting with len() but
// it is optimized to avoid parsing the entries
func (realFS) ReadDirCount(dir string) (int, error) {
buf := make([]byte, 4096)
fh, err := os.Open(dir)
if err != nil {
return 0, err
}
defer fh.Close()
openFilesCount := 0
for {
n, err := syscall.ReadDirent(int(fh.Fd()), buf)
if err != nil {
return 0, fmt.Errorf("ReadDirent() failed: %v", err)
}
if n == 0 {
break
}
openFilesCount += countDirEntries(buf, n)
}
// "." and ".." don't count as files to be counted
nDotFiles := 2
return openFilesCount - nDotFiles, err
}