blob: d3efcfe3d5a610e3cab592481914117a4f17b2d4 [file] [log] [blame]
khenaidooab1f7bd2019-11-14 14:00:27 -05001// Copyright 2015 The etcd Authors
2//
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
15package ioutil
16
17import (
18 "fmt"
19 "io"
20)
21
22// ReaderAndCloser implements io.ReadCloser interface by combining
23// reader and closer together.
24type ReaderAndCloser struct {
25 io.Reader
26 io.Closer
27}
28
29var (
30 ErrShortRead = fmt.Errorf("ioutil: short read")
31 ErrExpectEOF = fmt.Errorf("ioutil: expect EOF")
32)
33
34// NewExactReadCloser returns a ReadCloser that returns errors if the underlying
35// reader does not read back exactly the requested number of bytes.
36func NewExactReadCloser(rc io.ReadCloser, totalBytes int64) io.ReadCloser {
37 return &exactReadCloser{rc: rc, totalBytes: totalBytes}
38}
39
40type exactReadCloser struct {
41 rc io.ReadCloser
42 br int64
43 totalBytes int64
44}
45
46func (e *exactReadCloser) Read(p []byte) (int, error) {
47 n, err := e.rc.Read(p)
48 e.br += int64(n)
49 if e.br > e.totalBytes {
50 return 0, ErrExpectEOF
51 }
52 if e.br < e.totalBytes && n == 0 {
53 return 0, ErrShortRead
54 }
55 return n, err
56}
57
58func (e *exactReadCloser) Close() error {
59 if err := e.rc.Close(); err != nil {
60 return err
61 }
62 if e.br < e.totalBytes {
63 return ErrShortRead
64 }
65 return nil
66}