github.com/Files-com/files-sdk-go/v2@v2.1.2/file/proxyreader.go (about) 1 package file 2 3 import ( 4 "io" 5 ) 6 7 type ProxyReader interface { 8 io.ReadCloser 9 Len() int 10 BytesRead() int 11 Rewind() bool 12 } 13 14 type ProxyReaderAt struct { 15 io.ReaderAt 16 off int64 17 len int64 18 onRead func(i int64) 19 read int 20 closed bool 21 eof bool 22 } 23 24 type ProxyRead struct { 25 io.Reader 26 len int64 27 onRead func(i int64) 28 read int 29 closed bool 30 eof bool 31 } 32 33 func (x *ProxyReaderAt) Rewind() bool { 34 x.onRead(int64(-x.read)) 35 x.read = 0 36 return true 37 } 38 39 func (x *ProxyRead) Rewind() bool { 40 return x.read == 0 41 } 42 43 func (x *ProxyReaderAt) Len() int { 44 return int(x.len) 45 } 46 47 func (x *ProxyRead) Len() int { 48 return int(x.len) 49 } 50 51 func (x *ProxyReaderAt) BytesRead() int { 52 return x.read 53 } 54 55 func (x *ProxyRead) BytesRead() int { 56 return x.read 57 } 58 59 func (x *ProxyReaderAt) Seek(offset int64, whence int) (int64, error) { 60 x.onRead(-int64(x.read - int(offset))) // rewind progress 61 x.read = int(offset) 62 return offset, nil 63 } 64 65 func (x *ProxyReaderAt) Read(p []byte) (int, error) { 66 if x.closed { 67 x.onRead(-int64(x.read)) // rewind progress 68 x.read = 0 69 x.closed = false 70 } 71 72 if x.read == x.Len() { 73 return 0, io.EOF 74 } 75 var n int 76 var err error 77 if len(p) > x.Len()-x.read { 78 n, err = x.ReadAt(p[0:x.Len()-x.read], x.off+int64(x.read)) 79 } else { 80 n, err = x.ReadAt(p, x.off+int64(x.read)) 81 } 82 83 if err == io.EOF { 84 x.eof = true 85 } 86 87 if err != nil { 88 return n, err 89 } 90 91 x.read += n 92 if x.onRead != nil { 93 x.onRead(int64(n)) 94 } 95 return n, nil 96 } 97 98 func (x *ProxyRead) Read(p []byte) (int, error) { 99 if x.read == x.Len() || x.closed { 100 return 0, io.EOF 101 } 102 103 n, err := x.Reader.Read(p[0 : x.Len()-x.read]) 104 if err == io.EOF { 105 x.eof = true 106 } 107 108 if err != nil { 109 return n, err 110 } 111 112 x.read += n 113 if x.onRead != nil { 114 x.onRead(int64(n)) 115 } 116 117 return n, err 118 } 119 120 func (x *ProxyReaderAt) Close() error { 121 x.closed = true 122 return nil 123 } 124 125 func (x *ProxyRead) Close() error { 126 x.closed = true 127 return nil 128 }