2015-09-13 14:01:50 -04:00
|
|
|
package net
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
|
2015-10-08 08:46:18 -04:00
|
|
|
"github.com/v2ray/v2ray-core/common/alloc"
|
2015-10-07 17:50:56 -04:00
|
|
|
)
|
|
|
|
|
2015-10-11 08:46:12 -04:00
|
|
|
// ReadFrom reads from a reader and put all content to a buffer.
|
|
|
|
// If buffer is nil, ReadFrom creates a new normal buffer.
|
2015-10-08 08:46:18 -04:00
|
|
|
func ReadFrom(reader io.Reader, buffer *alloc.Buffer) (*alloc.Buffer, error) {
|
|
|
|
if buffer == nil {
|
|
|
|
buffer = alloc.NewBuffer()
|
2015-10-07 17:50:56 -04:00
|
|
|
}
|
2015-10-08 08:46:18 -04:00
|
|
|
nBytes, err := reader.Read(buffer.Value)
|
|
|
|
buffer.Slice(0, nBytes)
|
|
|
|
return buffer, err
|
2015-10-07 17:50:56 -04:00
|
|
|
}
|
|
|
|
|
2015-10-21 15:53:55 -04:00
|
|
|
// ReadAllBytes reads all bytes required from reader, if no error happens.
|
|
|
|
func ReadAllBytes(reader io.Reader, buffer []byte) (int, error) {
|
|
|
|
bytesRead := 0
|
|
|
|
bytesAsked := len(buffer)
|
|
|
|
for bytesRead < bytesAsked {
|
|
|
|
nBytes, err := reader.Read(buffer[bytesRead:])
|
|
|
|
bytesRead += nBytes
|
|
|
|
if err != nil {
|
|
|
|
return bytesRead, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return bytesRead, nil
|
|
|
|
}
|
|
|
|
|
2015-09-21 06:15:25 -04:00
|
|
|
// ReaderToChan dumps all content from a given reader to a chan by constantly reading it until EOF.
|
2015-10-08 08:46:18 -04:00
|
|
|
func ReaderToChan(stream chan<- *alloc.Buffer, reader io.Reader) error {
|
2015-10-11 05:43:31 -04:00
|
|
|
allocate := alloc.NewBuffer
|
|
|
|
large := false
|
2015-09-13 14:01:50 -04:00
|
|
|
for {
|
2015-10-11 05:43:31 -04:00
|
|
|
buffer, err := ReadFrom(reader, allocate())
|
2015-10-08 08:46:18 -04:00
|
|
|
if buffer.Len() > 0 {
|
|
|
|
stream <- buffer
|
|
|
|
} else {
|
|
|
|
buffer.Release()
|
2015-09-14 12:19:17 -04:00
|
|
|
}
|
2015-09-13 14:01:50 -04:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2015-10-11 05:43:31 -04:00
|
|
|
if buffer.IsFull() && !large {
|
|
|
|
allocate = alloc.NewLargeBuffer
|
|
|
|
large = true
|
|
|
|
} else if !buffer.IsFull() {
|
|
|
|
allocate = alloc.NewBuffer
|
|
|
|
large = false
|
|
|
|
}
|
2015-09-13 14:01:50 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-09-21 06:15:25 -04:00
|
|
|
// ChanToWriter dumps all content from a given chan to a writer until the chan is closed.
|
2015-10-08 08:46:18 -04:00
|
|
|
func ChanToWriter(writer io.Writer, stream <-chan *alloc.Buffer) error {
|
2015-09-13 14:01:50 -04:00
|
|
|
for buffer := range stream {
|
2015-10-09 07:07:42 -04:00
|
|
|
nBytes, err := writer.Write(buffer.Value)
|
2015-10-09 10:48:11 -04:00
|
|
|
if nBytes < buffer.Len() {
|
|
|
|
_, err = writer.Write(buffer.Value[nBytes:])
|
|
|
|
}
|
2015-10-08 08:46:18 -04:00
|
|
|
buffer.Release()
|
2015-09-13 14:01:50 -04:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|