github.com/imannamdari/v2ray-core/v5@v5.0.5/common/mux/reader.go (about)

     1  package mux
     2  
     3  import (
     4  	"io"
     5  
     6  	"github.com/imannamdari/v2ray-core/v5/common/buf"
     7  	"github.com/imannamdari/v2ray-core/v5/common/crypto"
     8  	"github.com/imannamdari/v2ray-core/v5/common/serial"
     9  )
    10  
    11  // PacketReader is an io.Reader that reads whole chunk of Mux frames every time.
    12  type PacketReader struct {
    13  	reader io.Reader
    14  	eof    bool
    15  }
    16  
    17  // NewPacketReader creates a new PacketReader.
    18  func NewPacketReader(reader io.Reader) *PacketReader {
    19  	return &PacketReader{
    20  		reader: reader,
    21  		eof:    false,
    22  	}
    23  }
    24  
    25  // ReadMultiBuffer implements buf.Reader.
    26  func (r *PacketReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
    27  	if r.eof {
    28  		return nil, io.EOF
    29  	}
    30  
    31  	size, err := serial.ReadUint16(r.reader)
    32  	if err != nil {
    33  		return nil, err
    34  	}
    35  
    36  	if size > buf.Size {
    37  		return nil, newError("packet size too large: ", size)
    38  	}
    39  
    40  	b := buf.New()
    41  	if _, err := b.ReadFullFrom(r.reader, int32(size)); err != nil {
    42  		b.Release()
    43  		return nil, err
    44  	}
    45  	r.eof = true
    46  	return buf.MultiBuffer{b}, nil
    47  }
    48  
    49  // NewStreamReader creates a new StreamReader.
    50  func NewStreamReader(reader *buf.BufferedReader) buf.Reader {
    51  	return crypto.NewChunkStreamReaderWithChunkCount(crypto.PlainChunkSizeParser{}, reader, 1)
    52  }