...
Run Format

Source file src/syscall/dirent_bsd_test.go

Documentation: syscall

     1  // Copyright 2018 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  // +build darwin,!arm,!arm64 dragonfly freebsd netbsd openbsd
     6  
     7  package syscall_test
     8  
     9  import (
    10  	"bytes"
    11  	"io/ioutil"
    12  	"os"
    13  	"path/filepath"
    14  	"sort"
    15  	"strconv"
    16  	"strings"
    17  	"syscall"
    18  	"testing"
    19  )
    20  
    21  func TestDirent(t *testing.T) {
    22  	const (
    23  		direntBufSize   = 2048
    24  		filenameMinSize = 11
    25  	)
    26  
    27  	d, err := ioutil.TempDir("", "dirent-test")
    28  	if err != nil {
    29  		t.Fatalf("tempdir: %v", err)
    30  	}
    31  	defer os.RemoveAll(d)
    32  	t.Logf("tmpdir: %s", d)
    33  
    34  	for i, c := range []byte("0123456789") {
    35  		name := string(bytes.Repeat([]byte{c}, filenameMinSize+i))
    36  		err = ioutil.WriteFile(filepath.Join(d, name), nil, 0644)
    37  		if err != nil {
    38  			t.Fatalf("writefile: %v", err)
    39  		}
    40  	}
    41  
    42  	buf := bytes.Repeat([]byte("DEADBEAF"), direntBufSize/8)
    43  	fd, err := syscall.Open(d, syscall.O_RDONLY, 0)
    44  	defer syscall.Close(fd)
    45  	if err != nil {
    46  		t.Fatalf("syscall.open: %v", err)
    47  	}
    48  	n, err := syscall.ReadDirent(fd, buf)
    49  	if err != nil {
    50  		t.Fatalf("syscall.readdir: %v", err)
    51  	}
    52  	buf = buf[:n]
    53  
    54  	names := make([]string, 0, 10)
    55  	for len(buf) > 0 {
    56  		var bc int
    57  		bc, _, names = syscall.ParseDirent(buf, -1, names)
    58  		buf = buf[bc:]
    59  	}
    60  
    61  	sort.Strings(names)
    62  	t.Logf("names: %q", names)
    63  
    64  	if len(names) != 10 {
    65  		t.Errorf("got %d names; expected 10", len(names))
    66  	}
    67  	for i, name := range names {
    68  		ord, err := strconv.Atoi(name[:1])
    69  		if err != nil {
    70  			t.Fatalf("names[%d] is non-integer %q: %v", i, names[i], err)
    71  		}
    72  		if expected := string(strings.Repeat(name[:1], filenameMinSize+ord)); name != expected {
    73  			t.Errorf("names[%d] is %q (len %d); expected %q (len %d)", i, name, len(name), expected, len(expected))
    74  		}
    75  	}
    76  }
    77  

View as plain text