You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
v2ray-core/common/buf/io.go

99 lines
2.4 KiB

8 years ago
package buf
import (
"io"
6 years ago
"syscall"
8 years ago
"time"
)
// Reader extends io.Reader with MultiBuffer.
type Reader interface {
// ReadMultiBuffer reads content from underlying reader, and put it into a MultiBuffer.
ReadMultiBuffer() (MultiBuffer, error)
}
// ErrReadTimeout is an error that happens with IO timeout.
var ErrReadTimeout = newError("IO timeout")
8 years ago
7 years ago
// TimeoutReader is a reader that returns error if Read() operation takes longer than the given timeout.
8 years ago
type TimeoutReader interface {
ReadMultiBufferTimeout(time.Duration) (MultiBuffer, error)
8 years ago
}
// Writer extends io.Writer with MultiBuffer.
type Writer interface {
// WriteMultiBuffer writes a MultiBuffer into underlying writer.
WriteMultiBuffer(MultiBuffer) error
}
8 years ago
8 years ago
// ReadFrom creates a Supplier to read from a given io.Reader.
8 years ago
func ReadFrom(reader io.Reader) Supplier {
return func(b []byte) (int, error) {
return reader.Read(b)
}
}
8 years ago
// ReadFullFrom creates a Supplier to read full buffer from a given io.Reader.
func ReadFullFrom(reader io.Reader, size int32) Supplier {
8 years ago
return func(b []byte) (int, error) {
return io.ReadFull(reader, b[:size])
}
}
// ReadAtLeastFrom create a Supplier to read at least size bytes from the given io.Reader.
func ReadAtLeastFrom(reader io.Reader, size int) Supplier {
return func(b []byte) (int, error) {
return io.ReadAtLeast(reader, b, size)
}
}
func WriteAllBytes(writer io.Writer, payload []byte) error {
for len(payload) > 0 {
n, err := writer.Write(payload)
if err != nil {
return err
}
payload = payload[n:]
}
return nil
}
// NewReader creates a new Reader.
// The Reader instance doesn't take the ownership of reader.
func NewReader(reader io.Reader) Reader {
if mr, ok := reader.(Reader); ok {
return mr
8 years ago
}
6 years ago
if useReadv {
if sc, ok := reader.(syscall.Conn); ok {
rawConn, err := sc.SyscallConn()
if err != nil {
newError("failed to get sysconn").Base(err).WriteToLog()
} else {
return NewReadVReader(reader, rawConn)
}
}
}
return NewBytesToBufferReader(reader)
}
// NewWriter creates a new Writer.
func NewWriter(writer io.Writer) Writer {
if mw, ok := writer.(Writer); ok {
return mw
8 years ago
}
return &BufferToBytesWriter{
Writer: writer,
}
}
7 years ago
// NewSequentialWriter returns a Writer that write Buffers in a MultiBuffer sequentially.
8 years ago
func NewSequentialWriter(writer io.Writer) Writer {
return &SequentialWriter{
Writer: writer,
8 years ago
}
}