1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2025-02-20 23:47:21 -05:00
v2fly/common/io/buffered_writer.go

82 lines
1.3 KiB
Go
Raw Normal View History

2016-02-26 23:45:33 +01:00
package io
import (
"io"
"sync"
2016-02-26 23:45:33 +01:00
"github.com/v2ray/v2ray-core/common/alloc"
)
type BufferedWriter struct {
sync.Mutex
2016-02-26 23:45:33 +01:00
writer io.Writer
buffer *alloc.Buffer
cached bool
}
func NewBufferedWriter(rawWriter io.Writer) *BufferedWriter {
return &BufferedWriter{
writer: rawWriter,
buffer: alloc.NewBuffer().Clear(),
cached: true,
}
}
func (this *BufferedWriter) Write(b []byte) (int, error) {
this.Lock()
defer this.Unlock()
if this.writer == nil {
return 0, io.EOF
}
2016-02-26 23:45:33 +01:00
if !this.cached {
return this.writer.Write(b)
}
nBytes, _ := this.buffer.Write(b)
if this.buffer.IsFull() {
2016-05-22 19:39:14 +02:00
go this.Flush()
2016-02-26 23:45:33 +01:00
}
return nBytes, nil
}
func (this *BufferedWriter) Flush() error {
this.Lock()
defer this.Unlock()
if this.writer == nil {
return io.EOF
}
2016-05-12 17:20:07 -07:00
defer this.buffer.Clear()
for !this.buffer.IsEmpty() {
nBytes, err := this.writer.Write(this.buffer.Value)
if err != nil {
return err
}
2016-02-26 23:45:33 +01:00
this.buffer.SliceFrom(nBytes)
}
2016-05-12 17:20:07 -07:00
return nil
2016-02-26 23:45:33 +01:00
}
func (this *BufferedWriter) Cached() bool {
return this.cached
}
func (this *BufferedWriter) SetCached(cached bool) {
this.cached = cached
if !cached && !this.buffer.IsEmpty() {
this.Flush()
2016-02-26 23:45:33 +01:00
}
}
func (this *BufferedWriter) Release() {
this.Flush()
this.Lock()
defer this.Unlock()
2016-02-26 23:45:33 +01:00
this.buffer.Release()
this.buffer = nil
this.writer = nil
2016-02-26 23:45:33 +01:00
}