Source file src/os/dir_unix.go

Documentation: os

     1  // Copyright 2009 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 aix dragonfly freebsd js,wasm linux nacl netbsd openbsd solaris
     6  
     7  package os
     8  
     9  import (
    10  	"io"
    11  	"runtime"
    12  	"syscall"
    13  )
    14  
    15  // Auxiliary information if the File describes a directory
    16  type dirInfo struct {
    17  	buf  []byte // buffer for directory I/O
    18  	nbuf int    // length of buf; return value from Getdirentries
    19  	bufp int    // location of next record in buf.
    20  }
    21  
    22  const (
    23  	// More than 5760 to work around https://golang.org/issue/24015.
    24  	blockSize = 8192
    25  )
    26  
    27  func (d *dirInfo) close() {}
    28  
    29  func (f *File) readdirnames(n int) (names []string, err error) {
    30  	// If this file has no dirinfo, create one.
    31  	if f.dirinfo == nil {
    32  		f.dirinfo = new(dirInfo)
    33  		// The buffer must be at least a block long.
    34  		f.dirinfo.buf = make([]byte, blockSize)
    35  	}
    36  	d := f.dirinfo
    37  
    38  	size := n
    39  	if size <= 0 {
    40  		size = 100
    41  		n = -1
    42  	}
    43  
    44  	names = make([]string, 0, size) // Empty with room to grow.
    45  	for n != 0 {
    46  		// Refill the buffer if necessary
    47  		if d.bufp >= d.nbuf {
    48  			d.bufp = 0
    49  			var errno error
    50  			d.nbuf, errno = f.pfd.ReadDirent(d.buf)
    51  			runtime.KeepAlive(f)
    52  			if errno != nil {
    53  				return names, wrapSyscallError("readdirent", errno)
    54  			}
    55  			if d.nbuf <= 0 {
    56  				break // EOF
    57  			}
    58  		}
    59  
    60  		// Drain the buffer
    61  		var nb, nc int
    62  		nb, nc, names = syscall.ParseDirent(d.buf[d.bufp:d.nbuf], n, names)
    63  		d.bufp += nb
    64  		n -= nc
    65  	}
    66  	if n >= 0 && len(names) == 0 {
    67  		return names, io.EOF
    68  	}
    69  	return names, nil
    70  }
    71  

View as plain text