-
Notifications
You must be signed in to change notification settings - Fork 3
/
gsreaderatcloser.go
64 lines (53 loc) · 1.42 KB
/
gsreaderatcloser.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package genomisc
import (
"context"
"cloud.google.com/go/storage"
)
// Decorates a Google Storage object handle with ReadAt
type GSReaderAtCloser struct {
*storage.ObjectHandle
Context context.Context
Closer *func() error
Reader *storage.Reader
}
func (o *GSReaderAtCloser) Read(p []byte) (n int, err error) {
if o.Reader == nil {
o.Reader, err = o.NewReader(o.Context)
if err != nil {
return 0, err
}
}
return o.Reader.Read(p)
}
// ReadAt satisfies io.ReaderAt. Note that this is dependent upon making p a
// buffer of the desired length to be read by NewRangeReader.
func (o *GSReaderAtCloser) ReadAt(p []byte, offset int64) (n int, err error) {
rdr, err := o.NewRangeReader(o.Context, offset, int64(len(p)))
if err != nil {
return 0, err
}
defer rdr.Close()
// Apparently with Google Cloud Storage we get to manually handle the fact
// that the reader will not read as much as we request, but instead may read
// less than that. And so here, we manually check if that's the case; if so,
// we loop until we have read at least as much as we requested.
var nBytes int
for {
innerBytes, err := rdr.Read(p[nBytes:])
nBytes += innerBytes
if err != nil {
return nBytes, err
}
if rdr.Remain() <= 0 {
break
}
}
return nBytes, nil
}
// Satisfies io.Closer. If o.close is not set, this is a nop.
func (o *GSReaderAtCloser) Close() error {
if o.Closer != nil {
return (*o.Closer)()
}
return nil
}