Fragment Description:



.
bytes.Buffer is a tremendously useful type, but it’s a bit large:
.
'sizeof -p bytes Buffer' = 112.
… and that is just the overhead, we haven’t put any data into the buffer yet.
This Friday’s challenge (see D.Cheney) was to write a replacement for bytes.Buffer that would implement io.ReadWriter (Interface) and allows the caller to discover the length and capacity of the buffer.
The kortschak Solution, June 2015, here.


ioReadWriterMiniBuffer

Go Playground

Last update, on 2015, Fri 9 Oct, 16:15:34

/* ... <== see fragment description ... */

package main

import (
    "io"
    "os"
)

// Buffer implements the io.ReadWriter interface
type Buffer []byte

func main() {
    buf := Buffer{}
    // confirm we meet the interface
    var _ io.ReadWriter = &buf
    // smoke test write
    if n, err := buf.Write([]byte("Testing this buffer\n")); n != 20 || err != nil {
        panic("Error on write")
    }
    io.CopyN(os.Stdout, &buf, 2)
    io.Copy(os.Stdout, &buf)
}
func (r *Buffer) Read(p []byte) (n int, err error) {
    // sign: copy(dst, src []Type) int
    n = copy(p, (*r)[0:])
    if n < len(*r) {
        *r = (*r)[n:]
    } else {
        *r = nil
    }
    if n < len(p) {
        return n, io.EOF
    }
    return n, nil
}
func (r *Buffer) Write(p []byte) (n int, err error) {
    // sign: append(slice []Type, elems ...Type) []Type
    *r = append(*r, p...)
    return len(p), nil
}

/* Expected Output:
Testing this buffer
*/



Comments