...

Source file src/syscall/getdirentries_test.go

Documentation: syscall

		 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 || freebsd || netbsd || openbsd
		 6  // +build darwin freebsd netbsd openbsd
		 7  
		 8  package syscall_test
		 9  
		10  import (
		11  	"fmt"
		12  	"os"
		13  	"path/filepath"
		14  	"sort"
		15  	"strings"
		16  	"syscall"
		17  	"testing"
		18  	"unsafe"
		19  )
		20  
		21  func TestGetdirentries(t *testing.T) {
		22  	for _, count := range []int{10, 1000} {
		23  		t.Run(fmt.Sprintf("n=%d", count), func(t *testing.T) {
		24  			testGetdirentries(t, count)
		25  		})
		26  	}
		27  }
		28  func testGetdirentries(t *testing.T, count int) {
		29  	if count > 100 && testing.Short() && os.Getenv("GO_BUILDER_NAME") == "" {
		30  		t.Skip("skipping in -short mode")
		31  	}
		32  	d := t.TempDir()
		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.Fatalf("WriteFile: %v", err)
		43  		}
		44  	}
		45  
		46  	// Read files using Getdirentries
		47  	var names2 []string
		48  	fd, err := syscall.Open(d, syscall.O_RDONLY, 0)
		49  	if err != nil {
		50  		t.Fatalf("Open: %v", err)
		51  	}
		52  	defer syscall.Close(fd)
		53  	var base uintptr
		54  	var buf [2048]byte
		55  	for {
		56  		n, err := syscall.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  			// If multiple Dirents are written into buf, sometimes when we reach the final one,
		66  			// we have cap(buf) < Sizeof(Dirent). So use an appropriate slice to copy from data.
		67  			var dirent syscall.Dirent
		68  			copy((*[unsafe.Sizeof(dirent)]byte)(unsafe.Pointer(&dirent))[:], data)
		69  
		70  			data = data[dirent.Reclen:]
		71  			name := make([]byte, dirent.Namlen)
		72  			for i := 0; i < int(dirent.Namlen); i++ {
		73  				name[i] = byte(dirent.Name[i])
		74  			}
		75  			names2 = append(names2, string(name))
		76  		}
		77  	}
		78  
		79  	names = append(names, ".", "..") // Getdirentries returns these also
		80  	sort.Strings(names)
		81  	sort.Strings(names2)
		82  	if strings.Join(names, ":") != strings.Join(names2, ":") {
		83  		t.Errorf("names don't match\n names: %q\nnames2: %q", names, names2)
		84  	}
		85  }
		86  

View as plain text