Skip to content

Commit

Permalink
Simplify and optimize RemoveMagicPrefixLine.
Browse files Browse the repository at this point in the history
If body has ")]}'\n" prefix, there's no need to use bytes.IndexByte to
find the first '\n' character, it's known to be at index 4 because
bytes.HasPrefix(body, []byte(")]}'\n")) was true.

Since this is called often, it's probably a good idea to factor out
[]byte(")]}'\n") into a package scope variable, instead of potentially
allocating once per RemoveMagicPrefixLine call.
  • Loading branch information
dmitshur authored May 16, 2017
1 parent 978d5a3 commit 09cddf5
Showing 1 changed file with 4 additions and 6 deletions.
10 changes: 4 additions & 6 deletions gerrit.go
Original file line number Diff line number Diff line change
Expand Up @@ -436,16 +436,14 @@ func (c *Client) DeleteRequest(urlStr string, body interface{}) (*Response, erro
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api.html#output
func RemoveMagicPrefixLine(body []byte) []byte {
if bytes.HasPrefix(body, []byte(")]}'\n")) {
index := bytes.IndexByte(body, '\n')
if index > -1 {
// +1 to catch the \n as well
body = body[(index + 1):]
}
if bytes.HasPrefix(body, magicPrefix) {
return body[5:]
}
return body
}

var magicPrefix = []byte(")]}'\n")

// CheckResponse checks the API response for errors, and returns them if present.
// A response is considered an error if it has a status code outside the 200 range.
// API error responses are expected to have no response body.
Expand Down

0 comments on commit 09cddf5

Please sign in to comment.