github.com/ratrocket/u-root@v0.0.0-20180201221235-1cf9f48ee2cf/pkg/null/null.go (about) 1 // Copyright 2012-2017 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 null extends ioutil.Discard and adds an io.WriteCloser 10 // and WriteNameCloser for use within u-root. 11 package null 12 13 import ( 14 "io" 15 "sync" 16 ) 17 18 type devNull int 19 20 // devNull implements ReaderFrom as an optimization so io.Copy to 21 // ioutil.Discard can avoid doing unnecessary work. 22 var _ io.ReaderFrom = devNull(0) 23 24 func (devNull) Write(p []byte) (int, error) { 25 return len(p), nil 26 } 27 28 func (devNull) Name() string { 29 return "null" 30 } 31 32 func (devNull) WriteString(s string) (int, error) { 33 return len(s), nil 34 } 35 36 var blackHolePool = sync.Pool{ 37 New: func() interface{} { 38 b := make([]byte, 8192) 39 return &b 40 }, 41 } 42 43 func (devNull) ReadFrom(r io.Reader) (n int64, err error) { 44 bufp := blackHolePool.Get().(*[]byte) 45 readSize := 0 46 for { 47 readSize, err = r.Read(*bufp) 48 n += int64(readSize) 49 if err != nil { 50 blackHolePool.Put(bufp) 51 if err == io.EOF { 52 return n, nil 53 } 54 return 55 } 56 } 57 } 58 59 func (devNull) Close() error { 60 return nil 61 } 62 63 // WriteNameCloser is the interface that groups Write, Close, and Name methods. 64 type WriteNameCloser interface { 65 io.Writer 66 io.Closer 67 Name() string 68 } 69 70 // WriteNameClose is an WriteNameCloser on which all Write and Close calls succeed 71 // without doing anything, and the Name call returns "null". 72 var WriteNameClose WriteNameCloser = devNull(0) 73 74 // WriteClose is an WriteCloser on which all Write and Close calls succeed 75 // without doing anything. 76 var WriteClose io.WriteCloser = devNull(0)