github.com/AndrienkoAleksandr/go@v0.0.19/src/os/file.go (about)

     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  // Package os provides a platform-independent interface to operating system
     6  // functionality. The design is Unix-like, although the error handling is
     7  // Go-like; failing calls return values of type error rather than error numbers.
     8  // Often, more information is available within the error. For example,
     9  // if a call that takes a file name fails, such as Open or Stat, the error
    10  // will include the failing file name when printed and will be of type
    11  // *PathError, which may be unpacked for more information.
    12  //
    13  // The os interface is intended to be uniform across all operating systems.
    14  // Features not generally available appear in the system-specific package syscall.
    15  //
    16  // Here is a simple example, opening a file and reading some of it.
    17  //
    18  //	file, err := os.Open("file.go") // For read access.
    19  //	if err != nil {
    20  //		log.Fatal(err)
    21  //	}
    22  //
    23  // If the open fails, the error string will be self-explanatory, like
    24  //
    25  //	open file.go: no such file or directory
    26  //
    27  // The file's data can then be read into a slice of bytes. Read and
    28  // Write take their byte counts from the length of the argument slice.
    29  //
    30  //	data := make([]byte, 100)
    31  //	count, err := file.Read(data)
    32  //	if err != nil {
    33  //		log.Fatal(err)
    34  //	}
    35  //	fmt.Printf("read %d bytes: %q\n", count, data[:count])
    36  //
    37  // Note: The maximum number of concurrent operations on a File may be limited by
    38  // the OS or the system. The number should be high, but exceeding it may degrade
    39  // performance or cause other issues.
    40  package os
    41  
    42  import (
    43  	"errors"
    44  	"internal/poll"
    45  	"internal/safefilepath"
    46  	"internal/testlog"
    47  	"io"
    48  	"io/fs"
    49  	"runtime"
    50  	"syscall"
    51  	"time"
    52  	"unsafe"
    53  )
    54  
    55  // Name returns the name of the file as presented to Open.
    56  func (f *File) Name() string { return f.name }
    57  
    58  // Stdin, Stdout, and Stderr are open Files pointing to the standard input,
    59  // standard output, and standard error file descriptors.
    60  //
    61  // Note that the Go runtime writes to standard error for panics and crashes;
    62  // closing Stderr may cause those messages to go elsewhere, perhaps
    63  // to a file opened later.
    64  var (
    65  	Stdin  = NewFile(uintptr(syscall.Stdin), "/dev/stdin")
    66  	Stdout = NewFile(uintptr(syscall.Stdout), "/dev/stdout")
    67  	Stderr = NewFile(uintptr(syscall.Stderr), "/dev/stderr")
    68  )
    69  
    70  // Flags to OpenFile wrapping those of the underlying system. Not all
    71  // flags may be implemented on a given system.
    72  const (
    73  	// Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified.
    74  	O_RDONLY int = syscall.O_RDONLY // open the file read-only.
    75  	O_WRONLY int = syscall.O_WRONLY // open the file write-only.
    76  	O_RDWR   int = syscall.O_RDWR   // open the file read-write.
    77  	// The remaining values may be or'ed in to control behavior.
    78  	O_APPEND int = syscall.O_APPEND // append data to the file when writing.
    79  	O_CREATE int = syscall.O_CREAT  // create a new file if none exists.
    80  	O_EXCL   int = syscall.O_EXCL   // used with O_CREATE, file must not exist.
    81  	O_SYNC   int = syscall.O_SYNC   // open for synchronous I/O.
    82  	O_TRUNC  int = syscall.O_TRUNC  // truncate regular writable file when opened.
    83  )
    84  
    85  // Seek whence values.
    86  //
    87  // Deprecated: Use io.SeekStart, io.SeekCurrent, and io.SeekEnd.
    88  const (
    89  	SEEK_SET int = 0 // seek relative to the origin of the file
    90  	SEEK_CUR int = 1 // seek relative to the current offset
    91  	SEEK_END int = 2 // seek relative to the end
    92  )
    93  
    94  // LinkError records an error during a link or symlink or rename
    95  // system call and the paths that caused it.
    96  type LinkError struct {
    97  	Op  string
    98  	Old string
    99  	New string
   100  	Err error
   101  }
   102  
   103  func (e *LinkError) Error() string {
   104  	return e.Op + " " + e.Old + " " + e.New + ": " + e.Err.Error()
   105  }
   106  
   107  func (e *LinkError) Unwrap() error {
   108  	return e.Err
   109  }
   110  
   111  // Read reads up to len(b) bytes from the File and stores them in b.
   112  // It returns the number of bytes read and any error encountered.
   113  // At end of file, Read returns 0, io.EOF.
   114  func (f *File) Read(b []byte) (n int, err error) {
   115  	if err := f.checkValid("read"); err != nil {
   116  		return 0, err
   117  	}
   118  	n, e := f.read(b)
   119  	return n, f.wrapErr("read", e)
   120  }
   121  
   122  // ReadAt reads len(b) bytes from the File starting at byte offset off.
   123  // It returns the number of bytes read and the error, if any.
   124  // ReadAt always returns a non-nil error when n < len(b).
   125  // At end of file, that error is io.EOF.
   126  func (f *File) ReadAt(b []byte, off int64) (n int, err error) {
   127  	if err := f.checkValid("read"); err != nil {
   128  		return 0, err
   129  	}
   130  
   131  	if off < 0 {
   132  		return 0, &PathError{Op: "readat", Path: f.name, Err: errors.New("negative offset")}
   133  	}
   134  
   135  	for len(b) > 0 {
   136  		m, e := f.pread(b, off)
   137  		if e != nil {
   138  			err = f.wrapErr("read", e)
   139  			break
   140  		}
   141  		n += m
   142  		b = b[m:]
   143  		off += int64(m)
   144  	}
   145  	return
   146  }
   147  
   148  // ReadFrom implements io.ReaderFrom.
   149  func (f *File) ReadFrom(r io.Reader) (n int64, err error) {
   150  	if err := f.checkValid("write"); err != nil {
   151  		return 0, err
   152  	}
   153  	n, handled, e := f.readFrom(r)
   154  	if !handled {
   155  		return genericReadFrom(f, r) // without wrapping
   156  	}
   157  	return n, f.wrapErr("write", e)
   158  }
   159  
   160  func genericReadFrom(f *File, r io.Reader) (int64, error) {
   161  	return io.Copy(fileWithoutReadFrom{f}, r)
   162  }
   163  
   164  // fileWithoutReadFrom implements all the methods of *File other
   165  // than ReadFrom. This is used to permit ReadFrom to call io.Copy
   166  // without leading to a recursive call to ReadFrom.
   167  type fileWithoutReadFrom struct {
   168  	*File
   169  }
   170  
   171  // This ReadFrom method hides the *File ReadFrom method.
   172  func (fileWithoutReadFrom) ReadFrom(fileWithoutReadFrom) {
   173  	panic("unreachable")
   174  }
   175  
   176  // Write writes len(b) bytes from b to the File.
   177  // It returns the number of bytes written and an error, if any.
   178  // Write returns a non-nil error when n != len(b).
   179  func (f *File) Write(b []byte) (n int, err error) {
   180  	if err := f.checkValid("write"); err != nil {
   181  		return 0, err
   182  	}
   183  	n, e := f.write(b)
   184  	if n < 0 {
   185  		n = 0
   186  	}
   187  	if n != len(b) {
   188  		err = io.ErrShortWrite
   189  	}
   190  
   191  	epipecheck(f, e)
   192  
   193  	if e != nil {
   194  		err = f.wrapErr("write", e)
   195  	}
   196  
   197  	return n, err
   198  }
   199  
   200  var errWriteAtInAppendMode = errors.New("os: invalid use of WriteAt on file opened with O_APPEND")
   201  
   202  // WriteAt writes len(b) bytes to the File starting at byte offset off.
   203  // It returns the number of bytes written and an error, if any.
   204  // WriteAt returns a non-nil error when n != len(b).
   205  //
   206  // If file was opened with the O_APPEND flag, WriteAt returns an error.
   207  func (f *File) WriteAt(b []byte, off int64) (n int, err error) {
   208  	if err := f.checkValid("write"); err != nil {
   209  		return 0, err
   210  	}
   211  	if f.appendMode {
   212  		return 0, errWriteAtInAppendMode
   213  	}
   214  
   215  	if off < 0 {
   216  		return 0, &PathError{Op: "writeat", Path: f.name, Err: errors.New("negative offset")}
   217  	}
   218  
   219  	for len(b) > 0 {
   220  		m, e := f.pwrite(b, off)
   221  		if e != nil {
   222  			err = f.wrapErr("write", e)
   223  			break
   224  		}
   225  		n += m
   226  		b = b[m:]
   227  		off += int64(m)
   228  	}
   229  	return
   230  }
   231  
   232  // Seek sets the offset for the next Read or Write on file to offset, interpreted
   233  // according to whence: 0 means relative to the origin of the file, 1 means
   234  // relative to the current offset, and 2 means relative to the end.
   235  // It returns the new offset and an error, if any.
   236  // The behavior of Seek on a file opened with O_APPEND is not specified.
   237  func (f *File) Seek(offset int64, whence int) (ret int64, err error) {
   238  	if err := f.checkValid("seek"); err != nil {
   239  		return 0, err
   240  	}
   241  	r, e := f.seek(offset, whence)
   242  	if e == nil && f.dirinfo != nil && r != 0 {
   243  		e = syscall.EISDIR
   244  	}
   245  	if e != nil {
   246  		return 0, f.wrapErr("seek", e)
   247  	}
   248  	return r, nil
   249  }
   250  
   251  // WriteString is like Write, but writes the contents of string s rather than
   252  // a slice of bytes.
   253  func (f *File) WriteString(s string) (n int, err error) {
   254  	b := unsafe.Slice(unsafe.StringData(s), len(s))
   255  	return f.Write(b)
   256  }
   257  
   258  // Mkdir creates a new directory with the specified name and permission
   259  // bits (before umask).
   260  // If there is an error, it will be of type *PathError.
   261  func Mkdir(name string, perm FileMode) error {
   262  	longName := fixLongPath(name)
   263  	e := ignoringEINTR(func() error {
   264  		return syscall.Mkdir(longName, syscallMode(perm))
   265  	})
   266  
   267  	if e != nil {
   268  		return &PathError{Op: "mkdir", Path: name, Err: e}
   269  	}
   270  
   271  	// mkdir(2) itself won't handle the sticky bit on *BSD and Solaris
   272  	if !supportsCreateWithStickyBit && perm&ModeSticky != 0 {
   273  		e = setStickyBit(name)
   274  
   275  		if e != nil {
   276  			Remove(name)
   277  			return e
   278  		}
   279  	}
   280  
   281  	return nil
   282  }
   283  
   284  // setStickyBit adds ModeSticky to the permission bits of path, non atomic.
   285  func setStickyBit(name string) error {
   286  	fi, err := Stat(name)
   287  	if err != nil {
   288  		return err
   289  	}
   290  	return Chmod(name, fi.Mode()|ModeSticky)
   291  }
   292  
   293  // Chdir changes the current working directory to the named directory.
   294  // If there is an error, it will be of type *PathError.
   295  func Chdir(dir string) error {
   296  	if e := syscall.Chdir(dir); e != nil {
   297  		testlog.Open(dir) // observe likely non-existent directory
   298  		return &PathError{Op: "chdir", Path: dir, Err: e}
   299  	}
   300  	if log := testlog.Logger(); log != nil {
   301  		wd, err := Getwd()
   302  		if err == nil {
   303  			log.Chdir(wd)
   304  		}
   305  	}
   306  	return nil
   307  }
   308  
   309  // Open opens the named file for reading. If successful, methods on
   310  // the returned file can be used for reading; the associated file
   311  // descriptor has mode O_RDONLY.
   312  // If there is an error, it will be of type *PathError.
   313  func Open(name string) (*File, error) {
   314  	return OpenFile(name, O_RDONLY, 0)
   315  }
   316  
   317  // Create creates or truncates the named file. If the file already exists,
   318  // it is truncated. If the file does not exist, it is created with mode 0666
   319  // (before umask). If successful, methods on the returned File can
   320  // be used for I/O; the associated file descriptor has mode O_RDWR.
   321  // If there is an error, it will be of type *PathError.
   322  func Create(name string) (*File, error) {
   323  	return OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0666)
   324  }
   325  
   326  // OpenFile is the generalized open call; most users will use Open
   327  // or Create instead. It opens the named file with specified flag
   328  // (O_RDONLY etc.). If the file does not exist, and the O_CREATE flag
   329  // is passed, it is created with mode perm (before umask). If successful,
   330  // methods on the returned File can be used for I/O.
   331  // If there is an error, it will be of type *PathError.
   332  func OpenFile(name string, flag int, perm FileMode) (*File, error) {
   333  	testlog.Open(name)
   334  	f, err := openFileNolog(name, flag, perm)
   335  	if err != nil {
   336  		return nil, err
   337  	}
   338  	f.appendMode = flag&O_APPEND != 0
   339  
   340  	return f, nil
   341  }
   342  
   343  // lstat is overridden in tests.
   344  var lstat = Lstat
   345  
   346  // Rename renames (moves) oldpath to newpath.
   347  // If newpath already exists and is not a directory, Rename replaces it.
   348  // OS-specific restrictions may apply when oldpath and newpath are in different directories.
   349  // Even within the same directory, on non-Unix platforms Rename is not an atomic operation.
   350  // If there is an error, it will be of type *LinkError.
   351  func Rename(oldpath, newpath string) error {
   352  	return rename(oldpath, newpath)
   353  }
   354  
   355  // Many functions in package syscall return a count of -1 instead of 0.
   356  // Using fixCount(call()) instead of call() corrects the count.
   357  func fixCount(n int, err error) (int, error) {
   358  	if n < 0 {
   359  		n = 0
   360  	}
   361  	return n, err
   362  }
   363  
   364  // checkWrapErr is the test hook to enable checking unexpected wrapped errors of poll.ErrFileClosing.
   365  // It is set to true in the export_test.go for tests (including fuzz tests).
   366  var checkWrapErr = false
   367  
   368  // wrapErr wraps an error that occurred during an operation on an open file.
   369  // It passes io.EOF through unchanged, otherwise converts
   370  // poll.ErrFileClosing to ErrClosed and wraps the error in a PathError.
   371  func (f *File) wrapErr(op string, err error) error {
   372  	if err == nil || err == io.EOF {
   373  		return err
   374  	}
   375  	if err == poll.ErrFileClosing {
   376  		err = ErrClosed
   377  	} else if checkWrapErr && errors.Is(err, poll.ErrFileClosing) {
   378  		panic("unexpected error wrapping poll.ErrFileClosing: " + err.Error())
   379  	}
   380  	return &PathError{Op: op, Path: f.name, Err: err}
   381  }
   382  
   383  // TempDir returns the default directory to use for temporary files.
   384  //
   385  // On Unix systems, it returns $TMPDIR if non-empty, else /tmp.
   386  // On Windows, it uses GetTempPath, returning the first non-empty
   387  // value from %TMP%, %TEMP%, %USERPROFILE%, or the Windows directory.
   388  // On Plan 9, it returns /tmp.
   389  //
   390  // The directory is neither guaranteed to exist nor have accessible
   391  // permissions.
   392  func TempDir() string {
   393  	return tempDir()
   394  }
   395  
   396  // UserCacheDir returns the default root directory to use for user-specific
   397  // cached data. Users should create their own application-specific subdirectory
   398  // within this one and use that.
   399  //
   400  // On Unix systems, it returns $XDG_CACHE_HOME as specified by
   401  // https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html if
   402  // non-empty, else $HOME/.cache.
   403  // On Darwin, it returns $HOME/Library/Caches.
   404  // On Windows, it returns %LocalAppData%.
   405  // On Plan 9, it returns $home/lib/cache.
   406  //
   407  // If the location cannot be determined (for example, $HOME is not defined),
   408  // then it will return an error.
   409  func UserCacheDir() (string, error) {
   410  	var dir string
   411  
   412  	switch runtime.GOOS {
   413  	case "windows":
   414  		dir = Getenv("LocalAppData")
   415  		if dir == "" {
   416  			return "", errors.New("%LocalAppData% is not defined")
   417  		}
   418  
   419  	case "darwin", "ios":
   420  		dir = Getenv("HOME")
   421  		if dir == "" {
   422  			return "", errors.New("$HOME is not defined")
   423  		}
   424  		dir += "/Library/Caches"
   425  
   426  	case "plan9":
   427  		dir = Getenv("home")
   428  		if dir == "" {
   429  			return "", errors.New("$home is not defined")
   430  		}
   431  		dir += "/lib/cache"
   432  
   433  	default: // Unix
   434  		dir = Getenv("XDG_CACHE_HOME")
   435  		if dir == "" {
   436  			dir = Getenv("HOME")
   437  			if dir == "" {
   438  				return "", errors.New("neither $XDG_CACHE_HOME nor $HOME are defined")
   439  			}
   440  			dir += "/.cache"
   441  		}
   442  	}
   443  
   444  	return dir, nil
   445  }
   446  
   447  // UserConfigDir returns the default root directory to use for user-specific
   448  // configuration data. Users should create their own application-specific
   449  // subdirectory within this one and use that.
   450  //
   451  // On Unix systems, it returns $XDG_CONFIG_HOME as specified by
   452  // https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html if
   453  // non-empty, else $HOME/.config.
   454  // On Darwin, it returns $HOME/Library/Application Support.
   455  // On Windows, it returns %AppData%.
   456  // On Plan 9, it returns $home/lib.
   457  //
   458  // If the location cannot be determined (for example, $HOME is not defined),
   459  // then it will return an error.
   460  func UserConfigDir() (string, error) {
   461  	var dir string
   462  
   463  	switch runtime.GOOS {
   464  	case "windows":
   465  		dir = Getenv("AppData")
   466  		if dir == "" {
   467  			return "", errors.New("%AppData% is not defined")
   468  		}
   469  
   470  	case "darwin", "ios":
   471  		dir = Getenv("HOME")
   472  		if dir == "" {
   473  			return "", errors.New("$HOME is not defined")
   474  		}
   475  		dir += "/Library/Application Support"
   476  
   477  	case "plan9":
   478  		dir = Getenv("home")
   479  		if dir == "" {
   480  			return "", errors.New("$home is not defined")
   481  		}
   482  		dir += "/lib"
   483  
   484  	default: // Unix
   485  		dir = Getenv("XDG_CONFIG_HOME")
   486  		if dir == "" {
   487  			dir = Getenv("HOME")
   488  			if dir == "" {
   489  				return "", errors.New("neither $XDG_CONFIG_HOME nor $HOME are defined")
   490  			}
   491  			dir += "/.config"
   492  		}
   493  	}
   494  
   495  	return dir, nil
   496  }
   497  
   498  // UserHomeDir returns the current user's home directory.
   499  //
   500  // On Unix, including macOS, it returns the $HOME environment variable.
   501  // On Windows, it returns %USERPROFILE%.
   502  // On Plan 9, it returns the $home environment variable.
   503  //
   504  // If the expected variable is not set in the environment, UserHomeDir
   505  // returns either a platform-specific default value or a non-nil error.
   506  func UserHomeDir() (string, error) {
   507  	env, enverr := "HOME", "$HOME"
   508  	switch runtime.GOOS {
   509  	case "windows":
   510  		env, enverr = "USERPROFILE", "%userprofile%"
   511  	case "plan9":
   512  		env, enverr = "home", "$home"
   513  	}
   514  	if v := Getenv(env); v != "" {
   515  		return v, nil
   516  	}
   517  	// On some geese the home directory is not always defined.
   518  	switch runtime.GOOS {
   519  	case "android":
   520  		return "/sdcard", nil
   521  	case "ios":
   522  		return "/", nil
   523  	}
   524  	return "", errors.New(enverr + " is not defined")
   525  }
   526  
   527  // Chmod changes the mode of the named file to mode.
   528  // If the file is a symbolic link, it changes the mode of the link's target.
   529  // If there is an error, it will be of type *PathError.
   530  //
   531  // A different subset of the mode bits are used, depending on the
   532  // operating system.
   533  //
   534  // On Unix, the mode's permission bits, ModeSetuid, ModeSetgid, and
   535  // ModeSticky are used.
   536  //
   537  // On Windows, only the 0200 bit (owner writable) of mode is used; it
   538  // controls whether the file's read-only attribute is set or cleared.
   539  // The other bits are currently unused. For compatibility with Go 1.12
   540  // and earlier, use a non-zero mode. Use mode 0400 for a read-only
   541  // file and 0600 for a readable+writable file.
   542  //
   543  // On Plan 9, the mode's permission bits, ModeAppend, ModeExclusive,
   544  // and ModeTemporary are used.
   545  func Chmod(name string, mode FileMode) error { return chmod(name, mode) }
   546  
   547  // Chmod changes the mode of the file to mode.
   548  // If there is an error, it will be of type *PathError.
   549  func (f *File) Chmod(mode FileMode) error { return f.chmod(mode) }
   550  
   551  // SetDeadline sets the read and write deadlines for a File.
   552  // It is equivalent to calling both SetReadDeadline and SetWriteDeadline.
   553  //
   554  // Only some kinds of files support setting a deadline. Calls to SetDeadline
   555  // for files that do not support deadlines will return ErrNoDeadline.
   556  // On most systems ordinary files do not support deadlines, but pipes do.
   557  //
   558  // A deadline is an absolute time after which I/O operations fail with an
   559  // error instead of blocking. The deadline applies to all future and pending
   560  // I/O, not just the immediately following call to Read or Write.
   561  // After a deadline has been exceeded, the connection can be refreshed
   562  // by setting a deadline in the future.
   563  //
   564  // If the deadline is exceeded a call to Read or Write or to other I/O
   565  // methods will return an error that wraps ErrDeadlineExceeded.
   566  // This can be tested using errors.Is(err, os.ErrDeadlineExceeded).
   567  // That error implements the Timeout method, and calling the Timeout
   568  // method will return true, but there are other possible errors for which
   569  // the Timeout will return true even if the deadline has not been exceeded.
   570  //
   571  // An idle timeout can be implemented by repeatedly extending
   572  // the deadline after successful Read or Write calls.
   573  //
   574  // A zero value for t means I/O operations will not time out.
   575  func (f *File) SetDeadline(t time.Time) error {
   576  	return f.setDeadline(t)
   577  }
   578  
   579  // SetReadDeadline sets the deadline for future Read calls and any
   580  // currently-blocked Read call.
   581  // A zero value for t means Read will not time out.
   582  // Not all files support setting deadlines; see SetDeadline.
   583  func (f *File) SetReadDeadline(t time.Time) error {
   584  	return f.setReadDeadline(t)
   585  }
   586  
   587  // SetWriteDeadline sets the deadline for any future Write calls and any
   588  // currently-blocked Write call.
   589  // Even if Write times out, it may return n > 0, indicating that
   590  // some of the data was successfully written.
   591  // A zero value for t means Write will not time out.
   592  // Not all files support setting deadlines; see SetDeadline.
   593  func (f *File) SetWriteDeadline(t time.Time) error {
   594  	return f.setWriteDeadline(t)
   595  }
   596  
   597  // SyscallConn returns a raw file.
   598  // This implements the syscall.Conn interface.
   599  func (f *File) SyscallConn() (syscall.RawConn, error) {
   600  	if err := f.checkValid("SyscallConn"); err != nil {
   601  		return nil, err
   602  	}
   603  	return newRawConn(f)
   604  }
   605  
   606  // DirFS returns a file system (an fs.FS) for the tree of files rooted at the directory dir.
   607  //
   608  // Note that DirFS("/prefix") only guarantees that the Open calls it makes to the
   609  // operating system will begin with "/prefix": DirFS("/prefix").Open("file") is the
   610  // same as os.Open("/prefix/file"). So if /prefix/file is a symbolic link pointing outside
   611  // the /prefix tree, then using DirFS does not stop the access any more than using
   612  // os.Open does. Additionally, the root of the fs.FS returned for a relative path,
   613  // DirFS("prefix"), will be affected by later calls to Chdir. DirFS is therefore not
   614  // a general substitute for a chroot-style security mechanism when the directory tree
   615  // contains arbitrary content.
   616  //
   617  // The directory dir must not be "".
   618  //
   619  // The result implements [io/fs.StatFS], [io/fs.ReadFileFS] and
   620  // [io/fs.ReadDirFS].
   621  func DirFS(dir string) fs.FS {
   622  	return dirFS(dir)
   623  }
   624  
   625  // containsAny reports whether any bytes in chars are within s.
   626  func containsAny(s, chars string) bool {
   627  	for i := 0; i < len(s); i++ {
   628  		for j := 0; j < len(chars); j++ {
   629  			if s[i] == chars[j] {
   630  				return true
   631  			}
   632  		}
   633  	}
   634  	return false
   635  }
   636  
   637  type dirFS string
   638  
   639  func (dir dirFS) Open(name string) (fs.File, error) {
   640  	fullname, err := dir.join(name)
   641  	if err != nil {
   642  		return nil, &PathError{Op: "stat", Path: name, Err: err}
   643  	}
   644  	f, err := Open(fullname)
   645  	if err != nil {
   646  		// DirFS takes a string appropriate for GOOS,
   647  		// while the name argument here is always slash separated.
   648  		// dir.join will have mixed the two; undo that for
   649  		// error reporting.
   650  		err.(*PathError).Path = name
   651  		return nil, err
   652  	}
   653  	return f, nil
   654  }
   655  
   656  // The ReadFile method calls the [ReadFile] function for the file
   657  // with the given name in the directory. The function provides
   658  // robust handling for small files and special file systems.
   659  // Through this method, dirFS implements [io/fs.ReadFileFS].
   660  func (dir dirFS) ReadFile(name string) ([]byte, error) {
   661  	fullname, err := dir.join(name)
   662  	if err != nil {
   663  		return nil, &PathError{Op: "readfile", Path: name, Err: err}
   664  	}
   665  	return ReadFile(fullname)
   666  }
   667  
   668  // ReadDir reads the named directory, returning all its directory entries sorted
   669  // by filename. Through this method, dirFS implements [io/fs.ReadDirFS].
   670  func (dir dirFS) ReadDir(name string) ([]DirEntry, error) {
   671  	fullname, err := dir.join(name)
   672  	if err != nil {
   673  		return nil, &PathError{Op: "readdir", Path: name, Err: err}
   674  	}
   675  	return ReadDir(fullname)
   676  }
   677  
   678  func (dir dirFS) Stat(name string) (fs.FileInfo, error) {
   679  	fullname, err := dir.join(name)
   680  	if err != nil {
   681  		return nil, &PathError{Op: "stat", Path: name, Err: err}
   682  	}
   683  	f, err := Stat(fullname)
   684  	if err != nil {
   685  		// See comment in dirFS.Open.
   686  		err.(*PathError).Path = name
   687  		return nil, err
   688  	}
   689  	return f, nil
   690  }
   691  
   692  // join returns the path for name in dir.
   693  func (dir dirFS) join(name string) (string, error) {
   694  	if dir == "" {
   695  		return "", errors.New("os: DirFS with empty root")
   696  	}
   697  	if !fs.ValidPath(name) {
   698  		return "", ErrInvalid
   699  	}
   700  	name, err := safefilepath.FromFS(name)
   701  	if err != nil {
   702  		return "", ErrInvalid
   703  	}
   704  	if IsPathSeparator(dir[len(dir)-1]) {
   705  		return string(dir) + name, nil
   706  	}
   707  	return string(dir) + string(PathSeparator) + name, nil
   708  }
   709  
   710  // ReadFile reads the named file and returns the contents.
   711  // A successful call returns err == nil, not err == EOF.
   712  // Because ReadFile reads the whole file, it does not treat an EOF from Read
   713  // as an error to be reported.
   714  func ReadFile(name string) ([]byte, error) {
   715  	f, err := Open(name)
   716  	if err != nil {
   717  		return nil, err
   718  	}
   719  	defer f.Close()
   720  
   721  	var size int
   722  	if info, err := f.Stat(); err == nil {
   723  		size64 := info.Size()
   724  		if int64(int(size64)) == size64 {
   725  			size = int(size64)
   726  		}
   727  	}
   728  	size++ // one byte for final read at EOF
   729  
   730  	// If a file claims a small size, read at least 512 bytes.
   731  	// In particular, files in Linux's /proc claim size 0 but
   732  	// then do not work right if read in small pieces,
   733  	// so an initial read of 1 byte would not work correctly.
   734  	if size < 512 {
   735  		size = 512
   736  	}
   737  
   738  	data := make([]byte, 0, size)
   739  	for {
   740  		if len(data) >= cap(data) {
   741  			d := append(data[:cap(data)], 0)
   742  			data = d[:len(data)]
   743  		}
   744  		n, err := f.Read(data[len(data):cap(data)])
   745  		data = data[:len(data)+n]
   746  		if err != nil {
   747  			if err == io.EOF {
   748  				err = nil
   749  			}
   750  			return data, err
   751  		}
   752  	}
   753  }
   754  
   755  // WriteFile writes data to the named file, creating it if necessary.
   756  // If the file does not exist, WriteFile creates it with permissions perm (before umask);
   757  // otherwise WriteFile truncates it before writing, without changing permissions.
   758  // Since WriteFile requires multiple system calls to complete, a failure mid-operation
   759  // can leave the file in a partially written state.
   760  func WriteFile(name string, data []byte, perm FileMode) error {
   761  	f, err := OpenFile(name, O_WRONLY|O_CREATE|O_TRUNC, perm)
   762  	if err != nil {
   763  		return err
   764  	}
   765  	_, err = f.Write(data)
   766  	if err1 := f.Close(); err1 != nil && err == nil {
   767  		err = err1
   768  	}
   769  	return err
   770  }