Skip to content

Commit

Permalink
more efficiently serialize YAML array into string
Browse files Browse the repository at this point in the history
  • Loading branch information
rhysd committed Aug 4, 2023
1 parent 70a782c commit 6f31c56
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 13 deletions.
8 changes: 5 additions & 3 deletions ast.go
Original file line number Diff line number Diff line change
Expand Up @@ -553,11 +553,13 @@ func (a *RawYAMLArray) Pos() *Pos {
}

func (a *RawYAMLArray) String() string {
qs := make([]string, 0, len(a.Elems))
var b quotesBuilder
b.inner.WriteRune('[')
for _, v := range a.Elems {
qs = append(qs, v.String())
b.append(v.String())
}
return fmt.Sprintf("[%s]", strings.Join(qs, ", "))
b.inner.WriteRune(']')
return b.build()
}

// RawYAMLString is raw YAML scalar value.
Expand Down
20 changes: 10 additions & 10 deletions quotes.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,33 +7,33 @@ import (
)

type quotesBuilder struct {
builder strings.Builder
buf []byte
comma bool
inner strings.Builder
buf []byte
comma bool
}

func (b *quotesBuilder) append(s string) {
if b.comma {
b.builder.WriteString(", ")
b.inner.WriteString(", ")
} else {
b.comma = true
}
b.buf = strconv.AppendQuote(b.buf[:0], s)
b.builder.Write(b.buf)
b.inner.Write(b.buf)
}

func (b *quotesBuilder) appendRune(r rune) {
if b.comma {
b.builder.WriteString(", ")
b.inner.WriteString(", ")
} else {
b.comma = true
}
b.buf = strconv.AppendQuoteRune(b.buf[:0], r)
b.builder.Write(b.buf)
b.inner.Write(b.buf)
}

func (b *quotesBuilder) build() string {
return b.builder.String()
return b.inner.String()
}

func quotes(ss []string) string {
Expand All @@ -52,7 +52,7 @@ func quotes(ss []string) string {
n += (l - 1) * 2 // comma
b := quotesBuilder{}
b.buf = make([]byte, 0, max)
b.builder.Grow(n)
b.inner.Grow(n)
for _, s := range ss {
b.append(s)
}
Expand Down Expand Up @@ -80,7 +80,7 @@ func quotesAll(sss ...[]string) string {
b.buf = make([]byte, 0, max)
n += (len(sss) - 1) * 2 // comma
if n > 0 {
b.builder.Grow(n)
b.inner.Grow(n)
}
for _, ss := range sss {
for _, s := range ss {
Expand Down

0 comments on commit 6f31c56

Please sign in to comment.