github.com/u-root/u-root@v7.0.1-0.20200915234505-ad7babab0a8e+incompatible/pkg/uio/null.go (about)

     1  // Copyright 2012-2019 the u-root 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  // Discard implementation copied from the Go project:
     6  // https://golang.org/src/io/ioutil/ioutil.go.
     7  // Copyright 2009 The Go Authors. All rights reserved.
     8  
     9  package uio
    10  
    11  import (
    12  	"io"
    13  	"sync"
    14  )
    15  
    16  type devNull int
    17  
    18  // devNull implements ReaderFrom as an optimization so io.Copy to
    19  // ioutil.Discard can avoid doing unnecessary work.
    20  var _ io.ReaderFrom = devNull(0)
    21  
    22  func (devNull) Write(p []byte) (int, error) {
    23  	return len(p), nil
    24  }
    25  
    26  func (devNull) Name() string {
    27  	return "null"
    28  }
    29  
    30  func (devNull) WriteString(s string) (int, error) {
    31  	return len(s), nil
    32  }
    33  
    34  var blackHolePool = sync.Pool{
    35  	New: func() interface{} {
    36  		b := make([]byte, 8192)
    37  		return &b
    38  	},
    39  }
    40  
    41  func (devNull) ReadFrom(r io.Reader) (n int64, err error) {
    42  	bufp := blackHolePool.Get().(*[]byte)
    43  	readSize := 0
    44  	for {
    45  		readSize, err = r.Read(*bufp)
    46  		n += int64(readSize)
    47  		if err != nil {
    48  			blackHolePool.Put(bufp)
    49  			if err == io.EOF {
    50  				return n, nil
    51  			}
    52  			return
    53  		}
    54  	}
    55  }
    56  
    57  func (devNull) Close() error {
    58  	return nil
    59  }
    60  
    61  // WriteNameCloser is the interface that groups Write, Close, and Name methods.
    62  type WriteNameCloser interface {
    63  	io.Writer
    64  	io.Closer
    65  	Name() string
    66  }
    67  
    68  // Discard is a WriteNameCloser on which all Write and Close calls succeed
    69  // without doing anything, and the Name call returns "null".
    70  var Discard WriteNameCloser = devNull(0)