ioutil.go at [ffd1ab7b0c]

File src/0dev.org/ioutil/ioutil.go artifact 98f8caa018 part of check-in ffd1ab7b0c


// Package ioutil contains various constructs for io operations
package ioutil

import (
	"io"
)

// An function alias type that implements io.Writer
type WriterFunc func([]byte) (int, error)

// Delegates the call to the WriterFunc while implementing io.Writer
func (w WriterFunc) Write(b []byte) (int, error) {
	return w(b)
}

// An function alias type that implements io.Reader
type ReaderFunc func([]byte) (int, error)

// Delegates the call to the WriterFunc while implementing io.Reader
func (r ReaderFunc) Read(b []byte) (int, error) {
	return r(b)
}

// Returns a reader that delegates calls to Read(...) while ensuring
// that the output buffer is never smaller than the required size
// and is downsized to a multiple of the required size if larger
func SizedReader(reader io.Reader, size int) io.Reader {
	var buffer []byte = make([]byte, 0, size)

	return ReaderFunc(func(output []byte) (int, error) {
		var (
			readCount int
			err       error
		)
	start:
		// Reply with the buffered data if there is any
		if len(buffer) > 0 {
			readCount = copy(output, buffer)

			// Advance the data in the buffer
			buffer = buffer[:copy(buffer, buffer[readCount:])]

			// Return count and error if we have read the whole buffer
			if len(buffer) == 0 {
				return readCount, err
			}

			// Do not propagate an error until the buffer is exhausted
			return readCount, nil
		}

		// Delegate if the buffer is empty and the destination buffer is large enough
		if len(output) >= size {
			return reader.Read(output[:(len(output)/size)*size])
		}

		// Perform a read into the buffer
		readCount, err = reader.Read(buffer[:size])

		// Size the buffer down to the read data size
		// and restart if we have successfully read some bytes
		buffer = buffer[:readCount]
		if len(buffer) > 0 {
			goto start
		}

		// Returning on err/misbehaving noop reader
		return 0, err
	})
}