| 1 | package buffer |
| 2 | |
| 3 | import ( |
| 4 | "encoding/gob" |
| 5 | "io" |
| 6 | ) |
| 7 | |
| 8 | type swap struct { |
| 9 | A BufferAt |
| 10 | B BufferAt |
| 11 | } |
| 12 | |
| 13 | // NewSwap creates a Buffer which writes to a until you write past a.Cap() |
| 14 | // then it io.Copy's from a to b and writes to b. |
| 15 | // Once the Buffer is empty again, it starts over writing to a. |
| 16 | // Note that if b.Cap() <= a.Cap() it will cause a panic, b is expected |
| 17 | // to be larger in order to accommodate writes past a.Cap(). |
| 18 | func NewSwap(a, b Buffer) Buffer { |
| 19 | return NewSwapAt(toBufferAt(a), toBufferAt(b)) |
| 20 | } |
| 21 | |
| 22 | // NewSwapAt creates a BufferAt which writes to a until you write past a.Cap() |
| 23 | // then it io.Copy's from a to b and writes to b. |
| 24 | // Once the Buffer is empty again, it starts over writing to a. |
| 25 | // Note that if b.Cap() <= a.Cap() it will cause a panic, b is expected |
| 26 | // to be larger in order to accommodate writes past a.Cap(). |
| 27 | func NewSwapAt(a, b BufferAt) BufferAt { |
| 28 | if b.Cap() <= a.Cap() { |
| 29 | panic("Buffer b must be larger than a.") |
| 30 | } |
| 31 | return &swap{A: a, B: b} |
| 32 | } |
| 33 | |
| 34 | func (buf *swap) Len() int64 { |
| 35 | return buf.A.Len() + buf.B.Len() |
| 36 | } |
| 37 | |
| 38 | func (buf *swap) Cap() int64 { |
| 39 | return buf.B.Cap() |
| 40 | } |
| 41 | |
| 42 | func (buf *swap) Read(p []byte) (n int, err error) { |
| 43 | if buf.A.Len() > 0 { |
| 44 | return buf.A.Read(p) |
| 45 | } |
| 46 | return buf.B.Read(p) |
| 47 | } |
| 48 | |
| 49 | func (buf *swap) ReadAt(p []byte, off int64) (n int, err error) { |
| 50 | if buf.A.Len() > 0 { |
| 51 | return buf.A.ReadAt(p, off) |
| 52 | } |
| 53 | return buf.B.ReadAt(p, off) |
| 54 | } |
| 55 | |
| 56 | func (buf *swap) Write(p []byte) (n int, err error) { |
| 57 | switch { |
| 58 | case buf.B.Len() > 0: |
| 59 | n, err = buf.B.Write(p) |
| 60 | |
| 61 | case buf.A.Len()+int64(len(p)) > buf.A.Cap(): |
| 62 | _, err = io.Copy(buf.B, buf.A) |
| 63 | if err == nil { |
| 64 | n, err = buf.B.Write(p) |
| 65 | } |
| 66 | |
| 67 | default: |
| 68 | n, err = buf.A.Write(p) |
| 69 | } |
| 70 | |
| 71 | return n, err |
| 72 | } |
| 73 | |
| 74 | func (buf *swap) WriteAt(p []byte, off int64) (n int, err error) { |
| 75 | switch { |
| 76 | case buf.B.Len() > 0: |
| 77 | n, err = buf.B.WriteAt(p, off) |
| 78 | |
| 79 | case off+int64(len(p)) > buf.A.Cap(): |
| 80 | _, err = io.Copy(buf.B, buf.A) |
| 81 | if err == nil { |
| 82 | n, err = buf.B.WriteAt(p, off) |
| 83 | } |
| 84 | |
| 85 | default: |
| 86 | n, err = buf.A.WriteAt(p, off) |
| 87 | } |
| 88 | |
| 89 | return n, err |
| 90 | } |
| 91 | |
| 92 | func (buf *swap) Reset() { |
| 93 | buf.A.Reset() |
| 94 | buf.B.Reset() |
| 95 | } |
| 96 | |
| 97 | func init() { |
| 98 | gob.Register(&swap{}) |
| 99 | } |