go icon indicating copy to clipboard operation
go copied to clipboard

proposal: io: add ZeroReader io.Reader

Open tmthrgd opened this issue 1 year ago • 4 comments

Needing to read a stream of zero-bytes is an ocassional use-case of an io.Reader. io.ZeroReader would be the /dev/zero counterpoint to /dev/null and io.Discard.

One particular use-case is with cipher.StreamReader to create a CSPRNG (this is the crypto/ecdsa use below).

I've proposed it be called io.ZeroReader, but it could also be called io.Zero or similar.


Proposed API:

package io

// ZeroReader is a Reader that reads an endless stream of zero-bytes.
var ZeroReader Reader = zeroReader{}

type zeroReader struct{} 
 
func (zeroReader) Read(p []byte) (int, error) { 
	for i := range p { 
		p[i] = 0 
	} 
	return len(p), nil 
}

There are two uses of this I can find in the standard library:

https://github.com/golang/go/blob/3a7a528c2d7ee0c7b2988a7aee0b9347e973cbed/src/archive/tar/reader.go#L811-L818

https://github.com/golang/go/blob/34ab0bcc5eaf97cc0aff11cfe782e4c174d52ef0/src/crypto/ecdsa/ecdsa.go#L446-L456

...and five more in test code: here and here.

Admittedly the archive/tar use could be written differently (it seems to be just zeroing a slice), but the crypto/ecdsa use does require it.

There are also two examples in the standard library of io.ReaderAt zeroing:

https://github.com/golang/go/blob/ea14d1b6e1167159dfc8408073ef411c3cf1d7e0/src/internal/xcoff/file.go#L449-L458

https://github.com/golang/go/blob/ea14d1b6e1167159dfc8408073ef411c3cf1d7e0/src/debug/pe/file.go#L185-L194

tmthrgd avatar Dec 15 '22 02:12 tmthrgd