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

fast read on first packet

This commit is contained in:
Darien Raymond 2017-11-08 22:23:21 +01:00
parent 14bc183754
commit d5fd7efa7e
No known key found for this signature in database
GPG Key ID: 7251FFA14BB18169
5 changed files with 29 additions and 18 deletions

View File

@ -57,18 +57,6 @@ func NewReader(reader io.Reader) Reader {
return &BytesToBufferReader{
reader: reader,
buffer: make([]byte, 32*1024),
}
}
func NewMergingReader(reader io.Reader) Reader {
return NewMergingReaderSize(reader, 32*1024)
}
func NewMergingReaderSize(reader io.Reader, size uint32) Reader {
return &BytesToBufferReader{
reader: reader,
buffer: make([]byte, size),
}
}

View File

@ -12,8 +12,30 @@ type BytesToBufferReader struct {
buffer []byte
}
func NewBytesToBufferReader(reader io.Reader) Reader {
return &BytesToBufferReader{
reader: reader,
}
}
func (r *BytesToBufferReader) readSmall() (MultiBuffer, error) {
b := New()
if err := b.Reset(ReadFrom(r.reader)); err != nil {
b.Release()
return nil, err
}
if b.IsFull() {
r.buffer = make([]byte, 32*1024)
}
return NewMultiBufferValue(b), nil
}
// Read implements Reader.Read().
func (r *BytesToBufferReader) Read() (MultiBuffer, error) {
if r.buffer == nil {
return r.readSmall()
}
nBytes, err := r.reader.Read(r.buffer)
if err != nil {
return nil, err

View File

@ -14,12 +14,13 @@ import (
func TestAdaptiveReader(t *testing.T) {
assert := With(t)
rawContent := make([]byte, 1024*1024)
buffer := bytes.NewBuffer(rawContent)
reader := NewReader(buffer)
reader := NewReader(bytes.NewReader(make([]byte, 1024*1024)))
b, err := reader.Read()
assert(err, IsNil)
assert(b.Len(), Equals, 2*1024)
b, err = reader.Read()
assert(err, IsNil)
assert(b.Len(), Equals, 32*1024)
}

View File

@ -23,7 +23,7 @@ type conn struct {
func (c *conn) ReadMultiBuffer() (buf.MultiBuffer, error) {
if c.mergingReader == nil {
c.mergingReader = buf.NewMergingReaderSize(c.Conn, 16*1024)
c.mergingReader = buf.NewBytesToBufferReader(c.Conn)
}
return c.mergingReader.Read()
}

View File

@ -49,7 +49,7 @@ func (c *connection) Read(b []byte) (int, error) {
func (c *connection) ReadMultiBuffer() (buf.MultiBuffer, error) {
if c.mergingReader == nil {
c.mergingReader = buf.NewMergingReader(c)
c.mergingReader = buf.NewBytesToBufferReader(c)
}
return c.mergingReader.Read()
}