|
| 1 | +package decoder |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "errors" |
| 6 | + "io" |
| 7 | + |
| 8 | + "github.com/yomorun/yomo/pkg/framing" |
| 9 | +) |
| 10 | + |
| 11 | +const ( |
| 12 | + minBuffSize = 3 * 1024 |
| 13 | + maxBuffSize = 16*1024*1024 + framing.FrameLengthFieldSize |
| 14 | +) |
| 15 | + |
| 16 | +// FrameDecoder defines a decoder for decoding frames which have a header of length. |
| 17 | +type FrameDecoder bufio.Scanner |
| 18 | + |
| 19 | +// Read reads next frame in bytes. |
| 20 | +// if rawFrame == true, it returns the raw frame without frame length field. |
| 21 | +func (p *FrameDecoder) Read(rawFrame bool) ([]byte, error) { |
| 22 | + scanner := (*bufio.Scanner)(p) |
| 23 | + if !scanner.Scan() { |
| 24 | + err := scanner.Err() |
| 25 | + if err == nil { |
| 26 | + err = io.EOF |
| 27 | + } |
| 28 | + return nil, err |
| 29 | + } |
| 30 | + |
| 31 | + // read raw frame |
| 32 | + if rawFrame { |
| 33 | + raw := scanner.Bytes()[framing.FrameLengthFieldSize:] |
| 34 | + return raw, nil |
| 35 | + } |
| 36 | + |
| 37 | + // read full frame includes frame length field. |
| 38 | + return scanner.Bytes(), nil |
| 39 | +} |
| 40 | + |
| 41 | +func doSplit(data []byte, eof bool) (advance int, token []byte, err error) { |
| 42 | + if eof { |
| 43 | + return |
| 44 | + } |
| 45 | + if len(data) < framing.FrameLengthFieldSize { |
| 46 | + return |
| 47 | + } |
| 48 | + frameLength := framing.ReadFrameLength(data) |
| 49 | + if frameLength < 1 { |
| 50 | + err = errors.New("invalid frame length") |
| 51 | + return |
| 52 | + } |
| 53 | + frameSize := frameLength + framing.FrameLengthFieldSize |
| 54 | + if frameSize <= len(data) { |
| 55 | + return frameSize, data[:frameSize], nil |
| 56 | + } |
| 57 | + return |
| 58 | +} |
| 59 | + |
| 60 | +// NewFrameDecoder creates a new frame decoder. |
| 61 | +func NewFrameDecoder(r io.Reader) *FrameDecoder { |
| 62 | + scanner := bufio.NewScanner(r) |
| 63 | + scanner.Split(doSplit) |
| 64 | + buf := make([]byte, 0, minBuffSize) |
| 65 | + scanner.Buffer(buf, maxBuffSize) |
| 66 | + return (*FrameDecoder)(scanner) |
| 67 | +} |
0 commit comments