Skip to content

Commit

Permalink
avoid repetitive memory allocations
Browse files Browse the repository at this point in the history
  • Loading branch information
petergardfjall committed Mar 31, 2022
1 parent 61eae9e commit fd7f58c
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 5 deletions.
11 changes: 8 additions & 3 deletions modules/git/foreachref/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ type Format struct {
// for each reference. fieldDelim and refDelim should be selected to not
// interfere with each other and to not be present in field values.
fieldDelim []byte
// fieldDelimStr is a string representation of fieldDelim. Used to save
// us from repetitive reallocation whenever we need the delimiter as a
// string.
fieldDelimStr string
// refDelim is the character sequence used to separate reference from
// each other in the output. fieldDelim and refDelim should be selected
// to not interfere with each other and to not be present in field
Expand All @@ -38,9 +42,10 @@ type Format struct {
// git-for-each-ref(1) for available fields.
func NewFormat(fieldNames ...string) Format {
return Format{
fieldNames: fieldNames,
fieldDelim: nullChar,
refDelim: dualNullChar,
fieldNames: fieldNames,
fieldDelim: nullChar,
fieldDelimStr: string(nullChar),
refDelim: dualNullChar,
}
}

Expand Down
4 changes: 2 additions & 2 deletions modules/git/foreachref/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func NewParser(r io.Reader, format Format) *Parser {
scanner.Split(
func(data []byte, atEOF bool) (advance int, token []byte, err error) {
// Scan until delimiter, marking end of reference.
delimIdx := bytes.Index(data, []byte(format.refDelim))
delimIdx := bytes.Index(data, format.refDelim)
if delimIdx >= 0 {
token := data[:delimIdx]
advance := delimIdx + len(format.refDelim)
Expand Down Expand Up @@ -93,7 +93,7 @@ func (p *Parser) parseRef(refBlock string) (map[string]string, error) {

fieldValues := make(map[string]string)

fields := strings.Split(refBlock, string(p.format.fieldDelim))
fields := strings.Split(refBlock, p.format.fieldDelimStr)
if len(fields) != len(p.format.fieldNames) {
return nil, fmt.Errorf("unexpected number of reference fields: wanted %d, was %d",
len(fields), len(p.format.fieldNames))
Expand Down

0 comments on commit fd7f58c

Please sign in to comment.