| 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 |
ocispec "github.com/opencontainers/image-spec/specs-go/v1" |
| 24 |
"oras.land/oras-go/v2/content" |
| 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 |
// Types returned by `io.NopCloser()`. |
| 48 |
var ( |
| 49 |
nopCloserType = reflect.TypeOf(io.NopCloser(nil)) |
| 50 |
nopCloserWriterToType = reflect.TypeOf(io.NopCloser(struct { |
| 51 |
io.Reader |
| 52 |
io.WriterTo |
| 53 |
}{})) |
| 54 |
) |
| 55 |
|
| 56 |
// UnwrapNopCloser unwraps the reader wrapped by `io.NopCloser()`. |
| 57 |
// Similar implementation can be found in the built-in package `net/http`. |
| 58 |
// Reference: https://github.com/golang/go/blob/go1.22.1/src/net/http/transfer.go#L1090-L1105 |
| 59 |
func UnwrapNopCloser(r io.Reader) io.Reader { |
| 60 |
switch reflect.TypeOf(r) { |
| 61 |
case nopCloserType, nopCloserWriterToType: |
| 62 |
return reflect.ValueOf(r).Field(0).Interface().(io.Reader) |
| 63 |
default: |
| 64 |
return r |
| 65 |
} |
| 66 |
} |