Skip to content

Commit 16b4535

Browse files
authored
Merge pull request #150 from orisano/master
feat: use strings.Replacer
2 parents c5df33d + 353573a commit 16b4535

File tree

1 file changed

+10
-24
lines changed

1 file changed

+10
-24
lines changed

expfmt/text_create.go

+10-24
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import (
1919
"io"
2020
"math"
2121
"strconv"
22+
"strings"
2223
"sync"
2324

2425
"github.com/prometheus/common/model"
@@ -416,32 +417,17 @@ func writeLabelPairs(
416417

417418
// writeEscapedString replaces '\' by '\\', new line character by '\n', and - if
418419
// includeDoubleQuote is true - '"' by '\"'.
420+
var (
421+
escaper = strings.NewReplacer("\\", `\\`, "\n", `\n`)
422+
quotedEscaper = strings.NewReplacer("\\", `\\`, "\n", `\n`, "\"", `\"`)
423+
)
424+
419425
func writeEscapedString(w enhancedWriter, v string, includeDoubleQuote bool) (int, error) {
420-
var (
421-
written, n int
422-
err error
423-
)
424-
for _, r := range v {
425-
switch r {
426-
case '\\':
427-
n, err = w.WriteString(`\\`)
428-
case '\n':
429-
n, err = w.WriteString(`\n`)
430-
case '"':
431-
if includeDoubleQuote {
432-
n, err = w.WriteString(`\"`)
433-
} else {
434-
n, err = w.WriteRune(r)
435-
}
436-
default:
437-
n, err = w.WriteRune(r)
438-
}
439-
written += n
440-
if err != nil {
441-
return written, err
442-
}
426+
if includeDoubleQuote {
427+
return quotedEscaper.WriteString(w, v)
428+
} else {
429+
return escaper.WriteString(w, v)
443430
}
444-
return written, nil
445431
}
446432

447433
// writeFloat is equivalent to fmt.Fprint with a float64 argument but hardcodes

0 commit comments

Comments
 (0)