v2ray-core/common/io/reader.go

63 lines
1.5 KiB
Go
Raw Normal View History

2016-01-29 13:39:55 +00:00
package io // import "github.com/v2ray/v2ray-core/common/io"
import (
"io"
2016-03-11 22:51:58 +00:00
"github.com/v2ray/v2ray-core/common"
2016-01-29 13:39:55 +00:00
"github.com/v2ray/v2ray-core/common/alloc"
)
// ReadFrom reads from a reader and put all content to a buffer.
// If buffer is nil, ReadFrom creates a new normal buffer.
func ReadFrom(reader io.Reader, buffer *alloc.Buffer) (*alloc.Buffer, error) {
if buffer == nil {
buffer = alloc.NewBuffer()
}
nBytes, err := reader.Read(buffer.Value)
buffer.Slice(0, nBytes)
return buffer, err
}
2016-02-06 21:28:35 +00:00
// Reader extends io.Reader with alloc.Buffer.
2016-01-29 13:39:55 +00:00
type Reader interface {
2016-04-12 19:43:13 +00:00
common.Releasable
2016-02-06 21:28:35 +00:00
// Read reads content from underlying reader, and put it into an alloc.Buffer.
2016-01-29 13:39:55 +00:00
Read() (*alloc.Buffer, error)
}
2016-02-06 21:28:35 +00:00
// AdaptiveReader is a Reader that adjusts its reading speed automatically.
2016-01-29 13:39:55 +00:00
type AdaptiveReader struct {
reader io.Reader
allocate func() *alloc.Buffer
}
2016-02-06 21:28:35 +00:00
// NewAdaptiveReader creates a new AdaptiveReader.
2016-04-28 20:31:33 +00:00
// The AdaptiveReader instance doesn't take the ownership of reader.
2016-01-29 13:39:55 +00:00
func NewAdaptiveReader(reader io.Reader) *AdaptiveReader {
return &AdaptiveReader{
reader: reader,
allocate: alloc.NewBuffer,
}
}
2016-02-06 21:28:35 +00:00
// Read implements Reader.Read().
2016-01-29 13:39:55 +00:00
func (this *AdaptiveReader) Read() (*alloc.Buffer, error) {
buffer, err := ReadFrom(this.reader, this.allocate())
2016-05-11 17:54:20 +00:00
if buffer.Len() >= alloc.BufferSize {
2016-01-29 13:39:55 +00:00
this.allocate = alloc.NewLargeBuffer
2016-05-11 17:54:20 +00:00
} else {
2016-01-29 13:39:55 +00:00
this.allocate = alloc.NewBuffer
}
if err != nil {
2016-02-01 11:22:29 +00:00
buffer.Release()
2016-01-29 13:39:55 +00:00
return nil, err
}
return buffer, nil
}
2016-03-11 22:51:58 +00:00
func (this *AdaptiveReader) Release() {
this.reader = nil
}