| 1 | package fsutil |
| 2 | |
| 3 | import ( |
| 4 | "io" |
| 5 | ) |
| 6 | |
| 7 | const chunkSize = 32 * 1024 |
| 8 | |
| 9 | type buffer struct { |
| 10 | chunks [][]byte |
| 11 | } |
| 12 | |
| 13 | func (b *buffer) alloc(n int) []byte { |
| 14 | if n > chunkSize { |
| 15 | buf := make([]byte, n) |
| 16 | b.chunks = append(b.chunks, buf) |
| 17 | return buf |
| 18 | } |
| 19 | |
| 20 | if len(b.chunks) != 0 { |
| 21 | lastChunk := b.chunks[len(b.chunks)-1] |
| 22 | l := len(lastChunk) |
| 23 | if l+n <= cap(lastChunk) { |
| 24 | lastChunk = lastChunk[:l+n] |
| 25 | b.chunks[len(b.chunks)-1] = lastChunk |
| 26 | return lastChunk[l : l+n] |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | buf := make([]byte, n, chunkSize) |
| 31 | b.chunks = append(b.chunks, buf) |
| 32 | return buf |
| 33 | } |
| 34 | |
| 35 | func (b *buffer) WriteTo(w io.Writer) (n int64, err error) { |
| 36 | for _, c := range b.chunks { |
| 37 | m, err := w.Write(c) |
| 38 | n += int64(m) |
| 39 | if err != nil { |
| 40 | return n, err |
| 41 | } |
| 42 | } |
| 43 | return n, nil |
| 44 | } |