func (bp *BytesPipe) Close() error {
	return bp.CloseWithError(nil)
}
Close causes further reads from a BytesPipe to return immediately.
package ioutils
import (
	"errors"
	"io"
	"sync"
)
const maxCap = 1e6
const blockThreshold = 1e6
var ErrClosed = errors.New("write to closed BytesPipe")
type BytesPipe struct {
	mu       sync.Mutex
	wait     *sync.Cond
	buf      [][]byte  
	lastRead int       
	bufLen   int       
	closeErr error     
}
func NewBytesPipe(buf []byte) *BytesPipe {
	if cap(buf) == 0 {
		buf = make([]byte, 0, 64)
	}
	bp := &BytesPipe{
		buf: [][]byte{buf[:0]},
	}
	bp.wait = sync.NewCond(&bp.mu)
	return bp
}
func (bp *BytesPipe) Write(p []byte) (int, error) {
	bp.mu.Lock()
	defer bp.mu.Unlock()
	written := 0
	for {
		if bp.closeErr != nil {
			return written, ErrClosed
		}
		b := bp.buf[len(bp.buf)-1]
		n := copy(b[len(b):cap(b)], p)
		bp.bufLen += n
		bp.buf[len(bp.buf)-1] = b[:len(b)+n]
		written += n
		if len(p) == n {
			break
		}
		p = p[n:]
		for bp.bufLen >= blockThreshold {
			bp.wait.Wait()
		}
		nextCap := 2 * cap(bp.buf[len(bp.buf)-1])
		if nextCap > maxCap {
			nextCap = maxCap
		}
		bp.buf = append(bp.buf, make([]byte, 0, nextCap))
	}
	bp.wait.Broadcast()
	return written, nil
}
func (bp *BytesPipe) CloseWithError(err error) error {
	bp.mu.Lock()
	if err != nil {
		bp.closeErr = err
	} else {
		bp.closeErr = io.EOF
	}
	bp.wait.Broadcast()
	bp.mu.Unlock()
	return nil
}