func (w *BufferedWriter) Write(b []byte) (int, error) {
	if len(b) == 0 {
		return 0, nil
	}
	w.Lock()
	defer w.Unlock()
	if !w.buffered {
		if writer, ok := w.writer.(io.Writer); ok {
			return writer.Write(b)
		}
	}
	totalBytes := 0
	for len(b) > 0 {
		if w.buffer == nil {
			w.buffer = New()
		}
		nBytes, err := w.buffer.Write(b)
		totalBytes += nBytes
		if err != nil {
			return totalBytes, err
		}
		if !w.buffered || w.buffer.IsFull() {
			if err := w.flushInternal(); err != nil {
				return totalBytes, err
			}
		}
		b = b[nBytes:]
	}
	return totalBytes, nil
}
Write implements io.Writer.
package buf
import (
	"io"
	"net"
	"sync"
	"github.com/v2fly/v2ray-core/v4/common"
	"github.com/v2fly/v2ray-core/v4/common/errors"
)
type BufferToBytesWriter struct {
	io.Writer
	cache [][]byte
}
func (w *BufferToBytesWriter) WriteMultiBuffer(mb MultiBuffer) error {
	defer ReleaseMulti(mb)
	size := mb.Len()
	if size == 0 {
		return nil
	}
	if len(mb) == 1 {
		return WriteAllBytes(w.Writer, mb[0].Bytes())
	}
	if cap(w.cache) < len(mb) {
		w.cache = make([][]byte, 0, len(mb))
	}
	bs := w.cache
	for _, b := range mb {
		bs = append(bs, b.Bytes())
	}
	defer func() {
		for idx := range bs {
			bs[idx] = nil
		}
	}()
	nb := net.Buffers(bs)
	for size > 0 {
		n, err := nb.WriteTo(w.Writer)
		if err != nil {
			return err
		}
		size -= int32(n)
	}
	return nil
}
func (w *BufferToBytesWriter) ReadFrom(reader io.Reader) (int64, error) {
	var sc SizeCounter
	err := Copy(NewReader(reader), w, CountSize(&sc))
	return sc.Size, err
}
type BufferedWriter struct {
	sync.Mutex
	writer   Writer
	buffer   *Buffer
	buffered bool
}
func NewBufferedWriter(writer Writer) *BufferedWriter {
	return &BufferedWriter{
		writer:   writer,
		buffer:   New(),
		buffered: true,
	}
}
func (w *BufferedWriter) WriteByte(c byte) error {
	return common.Error2(w.Write([]byte{c}))
}