aboutsummaryrefslogtreecommitdiff
path: root/cmp
diff options
context:
space:
mode:
authorJoe Tsai <joetsai@digital-static.net>2017-10-03 13:16:56 -0700
committerGitHub <noreply@github.com>2017-10-03 13:16:56 -0700
commit47d4c626df54478a76c53288bbb8c4be1ddbfa10 (patch)
tree232cf1a29b8045d04c8fc4e25b523a9f3c563086 /cmp
parent8ebdfab36c66d309e67b7799ac97db4e93f59358 (diff)
downloadgo-cmp-47d4c626df54478a76c53288bbb8c4be1ddbfa10.tar.gz
Adjust heuristics for using raw literals (#48)
Rather than searching for escape sequences, a better measure of whether to use raw literals or not is whether the raw literal form is shorter than the quoted string encoding. The assumption is that shorter string length is more readable, which is a reasonable (except for non-printable characters).
Diffstat (limited to 'cmp')
-rw-r--r--cmp/internal/value/format.go20
1 files changed, 14 insertions, 6 deletions
diff --git a/cmp/internal/value/format.go b/cmp/internal/value/format.go
index 74d7f0c..6de45c5 100644
--- a/cmp/internal/value/format.go
+++ b/cmp/internal/value/format.go
@@ -165,14 +165,22 @@ func formatAny(v reflect.Value, conf formatConfig, visited map[uintptr]bool) str
}
func formatString(s string) string {
- // Avoid performing quote-escaping if the string is already escaped.
- hasEscapes := strings.ContainsAny(s, `\`)
- allPrintable := strings.IndexFunc(s, unicode.IsPrint) >= 0
- rawAllowed := !strings.ContainsAny(s, "`\n")
- if hasEscapes && allPrintable && rawAllowed {
+ // Use quoted string if it the same length as a raw string literal.
+ // Otherwise, attempt to use the raw string form.
+ qs := strconv.Quote(s)
+ if len(qs) == 1+len(s)+1 {
+ return qs
+ }
+
+ // Disallow newlines to ensure output is a single line.
+ // Only allow printable runes for readability purposes.
+ rawInvalid := func(r rune) bool {
+ return r == '`' || r == '\n' || !unicode.IsPrint(r)
+ }
+ if strings.IndexFunc(s, rawInvalid) < 0 {
return "`" + s + "`"
}
- return strconv.Quote(s)
+ return qs
}
func formatPrimitive(t reflect.Type, v interface{}, conf formatConfig) string {