github.com/varialus/godfly@v0.0.0-20130904042352-1934f9f095ab/src/pkg/io/ioutil/ioutil.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 ioutil implements some I/O utility functions.
     6  package ioutil
     7  
     8  import (
     9  	"bytes"
    10  	"io"
    11  	"os"
    12  	"sort"
    13  )
    14  
    15  // readAll reads from r until an error or EOF and returns the data it read
    16  // from the internal buffer allocated with a specified capacity.
    17  func readAll(r io.Reader, capacity int64) (b []byte, err error) {
    18  	buf := bytes.NewBuffer(make([]byte, 0, capacity))
    19  	// If the buffer overflows, we will get bytes.ErrTooLarge.
    20  	// Return that as an error. Any other panic remains.
    21  	defer func() {
    22  		e := recover()
    23  		if e == nil {
    24  			return
    25  		}
    26  		if panicErr, ok := e.(error); ok && panicErr == bytes.ErrTooLarge {
    27  			err = panicErr
    28  		} else {
    29  			panic(e)
    30  		}
    31  	}()
    32  	_, err = buf.ReadFrom(r)
    33  	return buf.Bytes(), err
    34  }
    35  
    36  // ReadAll reads from r until an error or EOF and returns the data it read.
    37  // A successful call returns err == nil, not err == EOF. Because ReadAll is
    38  // defined to read from src until EOF, it does not treat an EOF from Read
    39  // as an error to be reported.
    40  func ReadAll(r io.Reader) ([]byte, error) {
    41  	return readAll(r, bytes.MinRead)
    42  }
    43  
    44  // ReadFile reads the file named by filename and returns the contents.
    45  // A successful call returns err == nil, not err == EOF. Because ReadFile
    46  // reads the whole file, it does not treat an EOF from Read as an error
    47  // to be reported.
    48  func ReadFile(filename string) ([]byte, error) {
    49  	f, err := os.Open(filename)
    50  	if err != nil {
    51  		return nil, err
    52  	}
    53  	defer f.Close()
    54  	// It's a good but not certain bet that FileInfo will tell us exactly how much to
    55  	// read, so let's try it but be prepared for the answer to be wrong.
    56  	var n int64
    57  
    58  	if fi, err := f.Stat(); err == nil {
    59  		// Don't preallocate a huge buffer, just in case.
    60  		if size := fi.Size(); size < 1e9 {
    61  			n = size
    62  		}
    63  	}
    64  	// As initial capacity for readAll, use n + a little extra in case Size is zero,
    65  	// and to avoid another allocation after Read has filled the buffer.  The readAll
    66  	// call will read into its allocated internal buffer cheaply.  If the size was
    67  	// wrong, we'll either waste some space off the end or reallocate as needed, but
    68  	// in the overwhelmingly common case we'll get it just right.
    69  	return readAll(f, n+bytes.MinRead)
    70  }
    71  
    72  // WriteFile writes data to a file named by filename.
    73  // If the file does not exist, WriteFile creates it with permissions perm;
    74  // otherwise WriteFile truncates it before writing.
    75  func WriteFile(filename string, data []byte, perm os.FileMode) error {
    76  	f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
    77  	if err != nil {
    78  		return err
    79  	}
    80  	n, err := f.Write(data)
    81  	if err == nil && n < len(data) {
    82  		err = io.ErrShortWrite
    83  	}
    84  	if err1 := f.Close(); err == nil {
    85  		err = err1
    86  	}
    87  	return err
    88  }
    89  
    90  // byName implements sort.Interface.
    91  type byName []os.FileInfo
    92  
    93  func (f byName) Len() int           { return len(f) }
    94  func (f byName) Less(i, j int) bool { return f[i].Name() < f[j].Name() }
    95  func (f byName) Swap(i, j int)      { f[i], f[j] = f[j], f[i] }
    96  
    97  // ReadDir reads the directory named by dirname and returns
    98  // a list of sorted directory entries.
    99  func ReadDir(dirname string) ([]os.FileInfo, error) {
   100  	f, err := os.Open(dirname)
   101  	if err != nil {
   102  		return nil, err
   103  	}
   104  	list, err := f.Readdir(-1)
   105  	f.Close()
   106  	if err != nil {
   107  		return nil, err
   108  	}
   109  	sort.Sort(byName(list))
   110  	return list, nil
   111  }
   112  
   113  type nopCloser struct {
   114  	io.Reader
   115  }
   116  
   117  func (nopCloser) Close() error { return nil }
   118  
   119  // NopCloser returns a ReadCloser with a no-op Close method wrapping
   120  // the provided Reader r.
   121  func NopCloser(r io.Reader) io.ReadCloser {
   122  	return nopCloser{r}
   123  }
   124  
   125  type devNull int
   126  
   127  // devNull implements ReaderFrom as an optimization so io.Copy to
   128  // ioutil.Discard can avoid doing unnecessary work.
   129  var _ io.ReaderFrom = devNull(0)
   130  
   131  func (devNull) Write(p []byte) (int, error) {
   132  	return len(p), nil
   133  }
   134  
   135  func (devNull) WriteString(s string) (int, error) {
   136  	return len(s), nil
   137  }
   138  
   139  func (devNull) ReadFrom(r io.Reader) (n int64, err error) {
   140  	buf := blackHole()
   141  	defer blackHolePut(buf)
   142  	readSize := 0
   143  	for {
   144  		readSize, err = r.Read(buf)
   145  		n += int64(readSize)
   146  		if err != nil {
   147  			if err == io.EOF {
   148  				return n, nil
   149  			}
   150  			return
   151  		}
   152  	}
   153  }
   154  
   155  // Discard is an io.Writer on which all Write calls succeed
   156  // without doing anything.
   157  var Discard io.Writer = devNull(0)