Skip to content

Commit

Permalink
caddyfile: Switch to strings.Builder for better performance
Browse files Browse the repository at this point in the history
  • Loading branch information
bbaa-bbaa committed Jan 25, 2024
1 parent b9c40e7 commit d4bc6e8
Showing 1 changed file with 12 additions and 13 deletions.
25 changes: 12 additions & 13 deletions caddyconfig/caddyfile/formatter.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package caddyfile
import (
"bytes"
"io"
"strings"
"unicode"
)

Expand Down Expand Up @@ -57,8 +58,8 @@ func Format(input []byte) []byte {

heredoc heredocState // whether we're in a heredoc
heredocEscaped bool // whether heredoc is escaped
heredocMarker []rune
heredocClosingMarker []rune
heredocMarker strings.Builder
heredocClosingMarker strings.Builder

nesting int // indentation level
)
Expand Down Expand Up @@ -99,10 +100,10 @@ func Format(input []byte) []byte {

if heredoc == heredocOpening {
if ch == '\n' {
if len(heredocMarker) > 0 && heredocMarkerRegexp.MatchString(string(heredocMarker)) {
if heredocMarker.Len() > 0 && heredocMarkerRegexp.MatchString(heredocMarker.String()) {
heredoc = heredocOpened
} else {
heredocMarker = nil
heredocMarker.Reset()
heredoc = heredocClosed
nextLine()
continue
Expand All @@ -112,25 +113,23 @@ func Format(input []byte) []byte {
}
if unicode.IsSpace(ch) {
// a space means it's just a regular token and not a heredoc
heredocMarker = nil
heredocMarker.Reset()
heredoc = heredocClosed
} else {
heredocMarker = append(heredocMarker, ch)
heredocMarker.WriteRune(ch)
write(ch)
continue
}
}
// if we're in a heredoc, all characters are read&write as-is
if heredoc == heredocOpened {
write(ch)
heredocClosingMarker = append(heredocClosingMarker, ch)
if len(heredocClosingMarker) > len(heredocMarker) {
heredocClosingMarker = heredocClosingMarker[1:]
}
heredocClosingMarker.WriteRune(ch)
// check if we're done
if string(heredocClosingMarker) == string(heredocMarker) {
heredocMarker = nil
heredocClosingMarker = nil
if heredocClosingMarker.Len() >= heredocMarker.Len() &&
heredocClosingMarker.String()[heredocClosingMarker.Len()-heredocMarker.Len():] == heredocMarker.String() {
heredocMarker.Reset()
heredocClosingMarker.Reset()
heredoc = heredocClosed
}
continue
Expand Down

0 comments on commit d4bc6e8

Please sign in to comment.