-
Notifications
You must be signed in to change notification settings - Fork 147
/
utils.go
71 lines (68 loc) · 1.9 KB
/
utils.go
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package yaml
import (
"fmt"
"io"
"strconv"
"strings"
)
// SafeString returns a string which is sufficiently quoted and escaped for YAML.
func SafeString(str string) string {
str = strings.Replace(str, "\\", "\\\\", -1)
str = strings.Replace(str, "\"", "\\\"", -1)
return "\"" + str + "\""
}
// PrintMatrix outputs a rectangular integer matrix in YAML text format.
//
// `indent` is the current YAML indentation level - the number of spaces.
// `name` is the name of the corresponding YAML block. If empty, no separate block is created.
// `fixNegative` changes all negative values to 0.
func PrintMatrix(writer io.Writer, matrix [][]int64, indent int, name string, fixNegative bool) {
// determine the maximum length of each value
var maxnum int64 = -(1 << 32)
var minnum int64 = 1 << 32
for _, status := range matrix {
for _, val := range status {
if val > maxnum {
maxnum = val
}
if val < minnum {
minnum = val
}
}
}
width := len(strconv.FormatInt(maxnum, 10))
if !fixNegative && minnum < 0 {
negativeWidth := len(strconv.FormatInt(minnum, 10))
if negativeWidth > width {
width = negativeWidth
}
}
last := len(matrix[len(matrix)-1])
if name != "" {
fmt.Fprintf(writer, "%s%s: |-\n", strings.Repeat(" ", indent), SafeString(name))
indent += 2
}
// print the resulting triangular matrix
first := true
for _, status := range matrix {
fmt.Fprint(writer, strings.Repeat(" ", indent-1))
for i := 0; i < last; i++ {
var val int64
if i < len(status) {
val = status[i]
// not sure why this sometimes happens...
// TODO(vmarkovtsev): find the root cause of tiny negative balances
if fixNegative && val < 0 {
val = 0
}
}
if !first {
fmt.Fprintf(writer, " %[1]*[2]d", width, val)
} else {
first = false
fmt.Fprintf(writer, " %d%s", val, strings.Repeat(" ", width-len(strconv.FormatInt(val, 10))))
}
}
fmt.Fprintln(writer)
}
}