1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-22 01:57:12 -05:00

merging reader

This commit is contained in:
Darien Raymond 2017-03-27 11:12:34 +02:00
parent eab2f1effc
commit cb0e29ccdb
No known key found for this signature in database
GPG Key ID: 7251FFA14BB18169
4 changed files with 54 additions and 7 deletions

View File

@ -41,14 +41,15 @@ func (b *Buffer) Clear() {
}
// AppendBytes appends one or more bytes to the end of the buffer.
func (b *Buffer) AppendBytes(bytes ...byte) {
b.Append(bytes)
func (b *Buffer) AppendBytes(bytes ...byte) int {
return b.Append(bytes)
}
// Append appends a byte array to the end of the buffer.
func (b *Buffer) Append(data []byte) {
func (b *Buffer) Append(data []byte) int {
nBytes := copy(b.v[b.end:], data)
b.end += nBytes
return nBytes
}
// AppendSupplier appends the content of a BytesWriter to the buffer.

View File

@ -2,6 +2,7 @@ package buf
import (
"io"
"time"
"v2ray.com/core/common/errors"
"v2ray.com/core/common/signal"
@ -13,6 +14,12 @@ type Reader interface {
Read() (*Buffer, error)
}
var ErrReadTimeout = errors.New("Buf: IO timeout.")
type TimeoutReader interface {
ReadTimeout(time.Duration) (*Buffer, error)
}
// Writer extends io.Writer with alloc.Buffer.
type Writer interface {
// Write writes an alloc.Buffer into underlying writer.

View File

@ -0,0 +1,42 @@
package buf
type MergingReader struct {
reader Reader
leftover *Buffer
}
func NewMergingReader(reader Reader) Reader {
return &MergingReader{
reader: reader,
}
}
func (r *MergingReader) Read() (*Buffer, error) {
if r.leftover != nil {
return r.leftover, nil
}
b, err := r.reader.Read()
if err != nil {
return nil, err
}
if b.IsFull() {
return b, nil
}
b2, err := r.reader.Read()
if err != nil {
return b, nil
}
nBytes := b.Append(b2.Bytes())
b2.SliceFrom(nBytes)
if b2.IsEmpty() {
b2.Release()
} else {
r.leftover = b2
}
return b, nil
}

View File

@ -2,7 +2,6 @@ package ray
import (
"context"
"errors"
"io"
"time"
@ -13,8 +12,6 @@ const (
bufferSize = 512
)
var ErrReadTimeout = errors.New("Ray: timeout.")
// NewRay creates a new Ray for direct traffic transport.
func NewRay(ctx context.Context) Ray {
return &directRay{
@ -101,7 +98,7 @@ func (v *Stream) ReadTimeout(timeout time.Duration) (*buf.Buffer, error) {
case <-v.err:
return nil, io.ErrClosedPipe
case <-time.After(timeout):
return nil, ErrReadTimeout
return nil, buf.ErrReadTimeout
}
}
}