From 4fc2a3b9db2837e7d7592e68c531e98eca6c3702 Mon Sep 17 00:00:00 2001 From: Shiwei Zhang Date: Tue, 19 Mar 2024 17:15:41 +0800 Subject: [PATCH 1/2] docs: refine documentation Signed-off-by: Shiwei Zhang --- internal/ioutil/io.go | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) 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 } } From 7099a5aad4732f7d397f088371781b682a070f75 Mon Sep 17 00:00:00 2001 From: Shiwei Zhang Date: Tue, 19 Mar 2024 17:21:58 +0800 Subject: [PATCH 2/2] test: add unit test for UnwrapNopCloser Signed-off-by: Shiwei Zhang --- internal/ioutil/io_test.go | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) 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",