Debian Codegraph @

helpers/tdutil/string.go

raw
1 // Copyright (c) 2019, Maxime Soulé
2 // All rights reserved.
3 //
4 // This source code is licensed under the BSD-style license found in the
5 // LICENSE file in the root directory of this source tree.
6
7 package tdutil
8
9 import (
10 "unicode"
11
12 "github.com/maxatome/go-testdeep/internal/spew"
13 )
14
15 // FormatString formats s to a printable string, trying to enclose it
16 // in double-quotes or back-quotes and defaulting to using [SpewString].
17 func FormatString(s string) string {
18 var unquotable, unbackquotable bool
19 for _, chr := range s {
20 if !unicode.IsPrint(chr) {
21 if chr != '\n' {
22 return SpewString(s)
23 }
24 unquotable = true
25 if unbackquotable {
26 break
27 }
28 continue
29 }
30 if chr == '"' {
31 unquotable = true
32 if unbackquotable {
33 break
34 }
35 } else if chr == '`' {
36 unbackquotable = true
37 if unquotable {
38 break
39 }
40 }
41 }
42 if unquotable {
43 if unbackquotable {
44 return SpewString(s)
45 }
46 return "`" + s + "`"
47 }
48 return `"` + s + `"`
49 }
50
51 // SpewString uses [spew.Sdump] to format val.
52 func SpewString(val any) string {
53 return spew.Sdump(val)
54 }