NewReadFull creates a new AsyncBuffer that reads from the given io.ReadCloser in foreground, blocking until all data is read. It returns an error if reading fails. When read fails, the reader is closed and resources are released immediately.
(r io.ReadCloser, dataLen int, finishFn ...context.CancelFunc)
| 101 | // in foreground, blocking until all data is read. It returns an error if reading |
| 102 | // fails. When read fails, the reader is closed and resources are released immediately. |
| 103 | func NewReadFull(r io.ReadCloser, dataLen int, finishFn ...context.CancelFunc) (*AsyncBuffer, error) { |
| 104 | ab := &AsyncBuffer{ |
| 105 | r: r, |
| 106 | dataLen: dataLen, |
| 107 | paused: NewLatch(), |
| 108 | chunkCond: NewCond(), |
| 109 | finishFn: finishFn, |
| 110 | } |
| 111 | |
| 112 | // Release the paused latch so that the reader can read all data immediately |
| 113 | ab.paused.Release() |
| 114 | |
| 115 | // Read all data in foreground |
| 116 | ab.readChunks() |
| 117 | |
| 118 | // If error occurred during reading, return it |
| 119 | if ab.Error() != nil { |
| 120 | ab.Close() // Reader should be closed and resources released |
| 121 | return nil, ab.Error() |
| 122 | } |
| 123 | |
| 124 | return ab, nil |
| 125 | } |
| 126 | |
| 127 | // WaitFor waits for the data to be ready at the given offset. nil means ok. |
| 128 | // It guarantees that the chunk at the given offset is ready to be read. |