github.com/opcr-io/oras-go/v2@v2.0.0-20231122155130-eb4260d8a0ae/internal/ioutil/io.go (about)

     1  /*
     2  Copyright The ORAS Authors.
     3  Licensed under the Apache License, Version 2.0 (the "License");
     4  you may not use this file except in compliance with the License.
     5  You may obtain a copy of the License at
     6  
     7  http://www.apache.org/licenses/LICENSE-2.0
     8  
     9  Unless required by applicable law or agreed to in writing, software
    10  distributed under the License is distributed on an "AS IS" BASIS,
    11  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  See the License for the specific language governing permissions and
    13  limitations under the License.
    14  */
    15  
    16  package ioutil
    17  
    18  import (
    19  	"fmt"
    20  	"io"
    21  	"reflect"
    22  
    23  	"github.com/opcr-io/oras-go/v2/content"
    24  	ocispec "github.com/opencontainers/image-spec/specs-go/v1"
    25  )
    26  
    27  // CloserFunc is the basic Close method defined in io.Closer.
    28  type CloserFunc func() error
    29  
    30  // Close performs close operation by the CloserFunc.
    31  func (fn CloserFunc) Close() error {
    32  	return fn()
    33  }
    34  
    35  // CopyBuffer copies from src to dst through the provided buffer
    36  // until either EOF is reached on src, or an error occurs.
    37  // The copied content is verified against the size and the digest.
    38  func CopyBuffer(dst io.Writer, src io.Reader, buf []byte, desc ocispec.Descriptor) error {
    39  	// verify while copying
    40  	vr := content.NewVerifyReader(src, desc)
    41  	if _, err := io.CopyBuffer(dst, vr, buf); err != nil {
    42  		return fmt.Errorf("copy failed: %w", err)
    43  	}
    44  	return vr.Verify()
    45  }
    46  
    47  // nopCloserType is the type of `io.NopCloser()`.
    48  var nopCloserType = reflect.TypeOf(io.NopCloser(nil))
    49  
    50  // UnwrapNopCloser unwraps the reader wrapped by `io.NopCloser()`.
    51  // Similar implementation can be found in the built-in package `net/http`.
    52  // Reference: https://github.com/golang/go/blob/go1.17.6/src/net/http/transfer.go#L423-L425
    53  func UnwrapNopCloser(rc io.Reader) io.Reader {
    54  	if reflect.TypeOf(rc) == nopCloserType {
    55  		return reflect.ValueOf(rc).Field(0).Interface().(io.Reader)
    56  	}
    57  	return rc
    58  }