diff --git a/internal/ioutil/io.go b/internal/ioutil/io.go index 105230d1..de41bda9 100644 --- a/internal/ioutil/io.go +++ b/internal/ioutil/io.go @@ -44,23 +44,23 @@ func CopyBuffer(dst io.Writer, src io.Reader, buf []byte, desc ocispec.Descripto return vr.Verify() } -// nopCloserType is the type of `io.NopCloser()`. -var nopCloserType = reflect.TypeOf(io.NopCloser(nil)) -// nopCloserWriterToType is the type of `io.nopCloserWriterTo` -var nopCloserWriterToType = reflect.TypeOf(io.NopCloser(struct { - io.Reader - io.WriterTo -}{})) +// Types returned by `io.NopCloser()`. +var ( + nopCloserType = reflect.TypeOf(io.NopCloser(nil)) + nopCloserWriterToType = reflect.TypeOf(io.NopCloser(struct { + io.Reader + io.WriterTo + }{})) +) -// UnwrapNopCloser returns the underlying reader if rc is a NopCloser -// else it simply returns rc. +// UnwrapNopCloser unwraps the reader wrapped by `io.NopCloser()`. // Similar implementation can be found in the built-in package `net/http`. // Reference: https://github.com/golang/go/blob/go1.22.1/src/net/http/transfer.go#L1090-L1105 -func UnwrapNopCloser(rc io.Reader) io.Reader { - switch reflect.TypeOf(rc) { +func UnwrapNopCloser(r io.Reader) io.Reader { + switch reflect.TypeOf(r) { case nopCloserType, nopCloserWriterToType: - return reflect.ValueOf(rc).Field(0).Interface().(io.Reader) + return reflect.ValueOf(r).Field(0).Interface().(io.Reader) default: - return rc + return r } } diff --git a/internal/ioutil/io_test.go b/internal/ioutil/io_test.go index 16a9873e..d27e8a5b 100644 --- a/internal/ioutil/io_test.go +++ b/internal/ioutil/io_test.go @@ -28,6 +28,14 @@ import ( ) func TestUnwrapNopCloser(t *testing.T) { + var reader struct { + io.Reader + } + var readerWithWriterTo struct { + io.Reader + io.WriterTo + } + tests := []struct { name string rc io.Reader @@ -37,9 +45,14 @@ func TestUnwrapNopCloser(t *testing.T) { name: "nil", }, { - name: "no-op closer", - rc: io.NopCloser(os.Stdin), - want: os.Stdin, + name: "no-op closer with plain io.Reader", + rc: io.NopCloser(reader), + want: reader, + }, + { + name: "no-op closer with io.WriteTo", + rc: io.NopCloser(readerWithWriterTo), + want: readerWithWriterTo, }, { name: "any ReadCloser",