golang.org/x/sys@v0.20.1-0.20240517151509-673e0f94c16d/unix/getdirentries_test.go (about) 1 // Copyright 2019 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 //go:build darwin || dragonfly || freebsd || openbsd || netbsd || zos 6 7 package unix_test 8 9 import ( 10 "fmt" 11 "os" 12 "path/filepath" 13 "sort" 14 "strings" 15 "testing" 16 17 "golang.org/x/sys/unix" 18 ) 19 20 func TestGetdirentries(t *testing.T) { 21 for _, count := range []int{10, 1000} { 22 t.Run(fmt.Sprintf("n=%d", count), func(t *testing.T) { 23 testGetdirentries(t, count) 24 }) 25 } 26 } 27 func testGetdirentries(t *testing.T, count int) { 28 if count > 100 && testing.Short() && os.Getenv("GO_BUILDER_NAME") == "" { 29 t.Skip("skipping in -short mode") 30 } 31 d := t.TempDir() 32 33 var names []string 34 for i := 0; i < count; i++ { 35 names = append(names, fmt.Sprintf("file%03d", i)) 36 } 37 38 // Make files in the temp directory 39 for _, name := range names { 40 err := os.WriteFile(filepath.Join(d, name), []byte("data"), 0) 41 if err != nil { 42 t.Fatal(err) 43 } 44 } 45 46 // Read files using Getdirentries 47 fd, err := unix.Open(d, unix.O_RDONLY, 0) 48 if err != nil { 49 t.Fatalf("Open: %v", err) 50 } 51 defer unix.Close(fd) 52 var base uintptr 53 var buf [2048]byte 54 names2 := make([]string, 0, count) 55 for { 56 n, err := unix.Getdirentries(fd, buf[:], &base) 57 if err != nil { 58 t.Fatalf("Getdirentries: %v", err) 59 } 60 if n == 0 { 61 break 62 } 63 data := buf[:n] 64 for len(data) > 0 { 65 var bc int 66 bc, _, names2 = unix.ParseDirent(data, -1, names2) 67 if bc == 0 && len(data) > 0 { 68 t.Fatal("no progress") 69 } 70 data = data[bc:] 71 } 72 } 73 74 sort.Strings(names) 75 sort.Strings(names2) 76 if strings.Join(names, ":") != strings.Join(names2, ":") { 77 t.Errorf("names don't match\n names: %q\nnames2: %q", names, names2) 78 } 79 }