Skip to content

Commit

Permalink
Backport readAll from later Go
Browse files Browse the repository at this point in the history
  • Loading branch information
dreamscached committed Feb 12, 2024
1 parent da7dc4a commit a936978
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
21 changes: 21 additions & 0 deletions io.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,24 @@ func readAllUntilZero(reader io.ByteReader) ([]byte, error) {
}
}
}

// readAll reads all bytes from reader.
// This is a backport from newer Go stdlib for sake of minequery's compatibility with Go 1.13.
func readAll(r io.Reader) ([]byte, error) {
b := make([]byte, 0, 512)
for {
n, err := r.Read(b[len(b):cap(b)])
b = b[:len(b)+n]
if err != nil {
if err == io.EOF {
err = nil
}
return b, err
}

if len(b) == cap(b) {
// Add more capacity (let append pick how much).
b = append(b, 0)[:len(b)]
}
}
}
8 changes: 4 additions & 4 deletions query.go
Original file line number Diff line number Diff line change
Expand Up @@ -371,7 +371,7 @@ func (p *Pinger) writeQueryFullStatPacket(conn *net.UDPConn, sessionID int32, to

func (p *Pinger) parseQueryHandshakeResponse(reader io.Reader) (int32, error) {
// Read all the remaining data in packet and ensure it has NUL terminator (if UseStrict)
token, _ := io.ReadAll(reader)
token, _ := readAll(reader)
if len(token) == 0 {
return 0, fmt.Errorf("challenge token is empty")
}
Expand All @@ -392,7 +392,7 @@ func (p *Pinger) parseQueryHandshakeResponse(reader io.Reader) (int32, error) {

func (p *Pinger) parseQueryBasicStatResponse(reader io.Reader) (*BasicQueryStatus, error) {
// Read all the remaining data and ensure it has NUL terminator (if UseStrict)
data, _ := io.ReadAll(reader)
data, _ := readAll(reader)
if len(data) == 0 {
return nil, fmt.Errorf("%w: empty response body", ErrInvalidStatus)
}
Expand Down Expand Up @@ -437,7 +437,7 @@ func (p *Pinger) parseQueryBasicStatResponse(reader io.Reader) (*BasicQueryStatu
}

// Read host as byte sequence
hostBytes, err := io.ReadAll(remReader)
hostBytes, err := readAll(remReader)
if err != nil {
return nil, err
}
Expand All @@ -454,7 +454,7 @@ func (p *Pinger) parseQueryBasicStatResponse(reader io.Reader) (*BasicQueryStatu

func (p *Pinger) parseQueryFullStatResponse(reader io.Reader) (*FullQueryStatus, error) {
// Read all the remaining data and ensure it has NUL terminator (if UseStrict)
data, _ := io.ReadAll(reader)
data, _ := readAll(reader)
if len(data) == 0 {
return nil, fmt.Errorf("%w: empty response body", ErrInvalidStatus)
}
Expand Down

0 comments on commit a936978

Please sign in to comment.