| 1 | // Package buffer implements a series of Buffers which can be composed to implement complicated buffering strategies |
| 2 | package buffer |
| 3 | |
| 4 | import ( |
| 5 | "io" |
| 6 | "os" |
| 7 | ) |
| 8 | |
| 9 | // Buffer is used to Write() data which will be Read() later. |
| 10 | type Buffer interface { |
| 11 | Len() int64 // How much data is Buffered in bytes |
| 12 | Cap() int64 // How much data can be Buffered at once in bytes. |
| 13 | io.Reader // Read() will read from the top of the buffer [io.EOF if empty] |
| 14 | io.Writer // Write() will write to the end of the buffer [io.ErrShortWrite if not enough space] |
| 15 | Reset() // Truncates the buffer, Len() == 0. |
| 16 | } |
| 17 | |
| 18 | // BufferAt is a buffer which supports io.ReaderAt and io.WriterAt |
| 19 | type BufferAt interface { |
| 20 | Buffer |
| 21 | io.ReaderAt |
| 22 | io.WriterAt |
| 23 | } |
| 24 | |
| 25 | func len64(p []byte) int64 { |
| 26 | return int64(len(p)) |
| 27 | } |
| 28 | |
| 29 | // Gap returns buf.Cap() - buf.Len() |
| 30 | func Gap(buf Buffer) int64 { |
| 31 | return buf.Cap() - buf.Len() |
| 32 | } |
| 33 | |
| 34 | // Full returns true iff buf.Len() == buf.Cap() |
| 35 | func Full(buf Buffer) bool { |
| 36 | return buf.Len() == buf.Cap() |
| 37 | } |
| 38 | |
| 39 | // Empty returns false iff buf.Len() == 0 |
| 40 | func Empty(buf Buffer) bool { |
| 41 | return buf.Len() == 0 |
| 42 | } |
| 43 | |
| 44 | // NewUnboundedBuffer returns a Buffer which buffers "mem" bytes to memory |
| 45 | // and then creates file's of size "file" to buffer above "mem" bytes. |
| 46 | func NewUnboundedBuffer(mem, file int64) Buffer { |
| 47 | return NewMulti(New(mem), NewPartition(NewFilePool(file, os.TempDir()))) |
| 48 | } |