Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix stream parser on long bytes #2

Merged
merged 1 commit into from
Aug 20, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 30 additions & 12 deletions parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package y3

import (
"bytes"
"errors"
"fmt"
"io"

Expand Down Expand Up @@ -34,33 +33,52 @@ func ReadPacket(reader io.Reader) ([]byte, error) {
break
}
}

// parse to y3.Length
var len int32
var length int32
codec := encoding.VarCodec{}
err = codec.DecodePVarInt32(lenbuf.Bytes(), &len)
err = codec.DecodePVarInt32(lenbuf.Bytes(), &length)
if err != nil {
return nil, err
}

// validate len decoded from stream
if len < 0 {
return nil, fmt.Errorf("y3.ReadPacket() get lenbuf=(%# x), decode len=(%v)", lenbuf.Bytes(), len)
if length < 0 {
return nil, fmt.Errorf("y3.ReadPacket() get lenbuf=(%# x), decode len=(%v)", lenbuf.Bytes(), length)
}

// write y3.Length bytes
buf.Write(lenbuf.Bytes())

// read next {len} bytes as y3.Value
valbuf := make([]byte, len)
p, err := reader.Read(valbuf)
if err != nil {
return nil, err
valbuf := bytes.Buffer{}

// every batch read 512 bytes, if next reads < 512, read
var count int
for {
batchReadSize := 512
var tmpbuf = []byte{}
if int(length)-count < batchReadSize {
tmpbuf = make([]byte, int(length)-count)
} else {
tmpbuf = make([]byte, batchReadSize)
}
p, err := reader.Read(tmpbuf)
count += p
if err != nil {
return nil, fmt.Errorf("y3 parse valbuf error: %v", err)
}
valbuf.Write(tmpbuf[:p])
if count == int(length) {
break
}
}
if p < int(len) {
return nil, errors.New("[y3] p should == len when getting y3 value buffer")

if count < int(length) {
return nil, fmt.Errorf("[y3] p should == len when getting y3 value buffer, len=%d, p=%d", length, count)
}
// write y3.Value bytes
buf.Write(valbuf)
buf.Write(valbuf.Bytes())

return buf.Bytes(), nil
}
Expand Down