forked from viamrobotics/goutils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathio.go
50 lines (45 loc) · 1.01 KB
/
io.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package utils
import (
"context"
"io"
)
// ContextCloser is a Closer with a context argument.
type ContextCloser interface {
Close(ctx context.Context) error
}
// TryClose attempts to close the target if it implements
// the right interface.
func TryClose(ctx context.Context, target interface{}) error {
switch t := target.(type) {
case io.Closer:
return t.Close()
case ContextCloser:
return t.Close(ctx)
case interface{ Close() }:
t.Close()
return nil
default:
return nil
}
}
// ReadBytes ensures that all bytes requested to be read
// are read into a slice unless an error occurs. If the reader
// never returns the amount of bytes requested, this will block
// until the given context is done.
func ReadBytes(ctx context.Context, r io.Reader, toRead int) ([]byte, error) {
buf := make([]byte, toRead)
pos := 0
for pos < toRead {
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
n, err := r.Read(buf[pos:])
if err != nil {
return nil, err
}
pos += n
}
return buf, nil
}