ReadFrom reads data from r until EOF and appends it to the buffer, growing the buffer as needed. The return value n is the number of bytes read. Any error except io.EOF encountered during the read is also returned. If the buffer becomes too large, ReadFrom will panic with ErrTooLarge.
(r io.Reader)
| 200 | // error except io.EOF encountered during the read is also returned. If the |
| 201 | // buffer becomes too large, ReadFrom will panic with ErrTooLarge. |
| 202 | func (b *Buffer) ReadFrom(r io.Reader) (n int64, err error) { |
| 203 | // If buffer is empty, reset to recover space. |
| 204 | if b.off >= len(b.buf) { |
| 205 | b.Truncate(0) |
| 206 | } |
| 207 | for { |
| 208 | if free := cap(b.buf) - len(b.buf); free < minRead { |
| 209 | // not enough space at end |
| 210 | newBuf := b.buf |
| 211 | if b.off+free < minRead { |
| 212 | // not enough space using beginning of buffer; |
| 213 | // double buffer capacity |
| 214 | newBuf = makeSlice(2*cap(b.buf) + minRead) |
| 215 | } |
| 216 | copy(newBuf, b.buf[b.off:]) |
| 217 | Pool(b.buf) |
| 218 | b.buf = newBuf[:len(b.buf)-b.off] |
| 219 | b.off = 0 |
| 220 | } |
| 221 | m, e := r.Read(b.buf[len(b.buf):cap(b.buf)]) |
| 222 | b.buf = b.buf[0 : len(b.buf)+m] |
| 223 | n += int64(m) |
| 224 | if e == io.EOF { |
| 225 | break |
| 226 | } |
| 227 | if e != nil { |
| 228 | return n, e |
| 229 | } |
| 230 | } |
| 231 | return n, nil // err is EOF, so return nil explicitly |
| 232 | } |
| 233 | |
| 234 | // WriteTo writes data to w until the buffer is drained or an error occurs. |
| 235 | // The return value n is the number of bytes written; it always fits into an |