File: string.go

package info (click to toggle)
golang-github-maxatome-go-testdeep 1.14.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,416 kB
  • sloc: perl: 1,012; yacc: 130; makefile: 2
file content (55 lines) | stat: -rw-r--r-- 1,097 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// Copyright (c) 2019, Maxime Soulé
// All rights reserved.
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.

package tdutil

import (
	"strings"
	"unicode"

	"github.com/davecgh/go-spew/spew"
)

// FormatString formats s to a printable string, trying to enclose it
// in double-quotes or back-quotes and defaulting to using [SpewString].
func FormatString(s string) string {
	var unquotable, unbackquotable bool
	for _, chr := range s {
		if !unicode.IsPrint(chr) {
			if chr != '\n' {
				return SpewString(s)
			}
			unquotable = true
			if unbackquotable {
				break
			}
			continue
		}
		if chr == '"' {
			unquotable = true
			if unbackquotable {
				break
			}
		} else if chr == '`' {
			unbackquotable = true
			if unquotable {
				break
			}
		}
	}
	if unquotable {
		if unbackquotable {
			return SpewString(s)
		}
		return "`" + s + "`"
	}
	return `"` + s + `"`
}

// SpewString uses [spew.Sdump] to format val.
func SpewString(val any) string {
	return strings.TrimRight(spew.Sdump(val), "\n")
}