Skip to content

Commit 5e300b1

Browse files
committed
parser: avoid excessive memory usage and bogus type conversions
Don't reallocate memory again for each string append. Remove conversion between strings and byte slices where they are actually reconverted back right away. Signed-off-by: Tonis Tiigi <[email protected]>
1 parent bcc3c98 commit 5e300b1

File tree

1 file changed

+12
-8
lines changed

1 file changed

+12
-8
lines changed

frontend/dockerfile/parser/parser.go

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -283,6 +283,7 @@ func Parse(rwc io.Reader) (*Result, error) {
283283
scanner.Split(scanLines)
284284
warnings := []Warning{}
285285
var comments []string
286+
buf := &bytes.Buffer{}
286287

287288
var err error
288289
for scanner.Scan() {
@@ -306,10 +307,12 @@ func Parse(rwc io.Reader) (*Result, error) {
306307
currentLine++
307308

308309
startLine := currentLine
309-
line, isEndOfLine := trimContinuationCharacter(string(bytesRead), d)
310-
if isEndOfLine && line == "" {
310+
bytesRead, isEndOfLine := trimContinuationCharacter(bytesRead, d)
311+
if isEndOfLine && len(bytesRead) == 0 {
311312
continue
312313
}
314+
buf.Reset()
315+
buf.Write(bytesRead)
313316

314317
var hasEmptyContinuationLine bool
315318
for !isEndOfLine && scanner.Scan() {
@@ -328,11 +331,12 @@ func Parse(rwc io.Reader) (*Result, error) {
328331
continue
329332
}
330333

331-
continuationLine := string(bytesRead)
332-
continuationLine, isEndOfLine = trimContinuationCharacter(continuationLine, d)
333-
line += continuationLine
334+
bytesRead, isEndOfLine = trimContinuationCharacter(bytesRead, d)
335+
buf.Write(bytesRead)
334336
}
335337

338+
line := buf.String()
339+
336340
if hasEmptyContinuationLine {
337341
warnings = append(warnings, Warning{
338342
Short: "Empty continuation line found in: " + line,
@@ -513,9 +517,9 @@ func isEmptyContinuationLine(line []byte) bool {
513517

514518
var utf8bom = []byte{0xEF, 0xBB, 0xBF}
515519

516-
func trimContinuationCharacter(line string, d *directives) (string, bool) {
517-
if d.lineContinuationRegex.MatchString(line) {
518-
line = d.lineContinuationRegex.ReplaceAllString(line, "$1")
520+
func trimContinuationCharacter(line []byte, d *directives) ([]byte, bool) {
521+
if d.lineContinuationRegex.Match(line) {
522+
line = d.lineContinuationRegex.ReplaceAll(line, []byte("$1"))
519523
return line, false
520524
}
521525
return line, true

0 commit comments

Comments
 (0)