/
util.go
94 lines (86 loc) · 1.75 KB
/
util.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package pb
import (
"bytes"
"fmt"
"github.com/mattn/go-runewidth"
"math"
"regexp"
//"unicode/utf8"
)
const (
_KiB = 1024
_MiB = 1048576
_GiB = 1073741824
_TiB = 1099511627776
)
var ctrlFinder = regexp.MustCompile("\x1b\x5b[0-9]+\x6d")
func CellCount(s string) int {
n := runewidth.StringWidth(s)
for _, sm := range ctrlFinder.FindAllString(s, -1) {
n -= runewidth.StringWidth(sm)
}
return n
}
func StripString(s string, w int) string {
l := CellCount(s)
if l <= w {
return s
}
var buf = bytes.NewBuffer(make([]byte, 0, len(s)))
StripStringToBuffer(s, w, buf)
return buf.String()
}
func StripStringToBuffer(s string, w int, buf *bytes.Buffer) {
var seqs = ctrlFinder.FindAllStringIndex(s, -1)
mainloop:
for i, r := range s {
for _, seq := range seqs {
if i >= seq[0] && i < seq[1] {
buf.WriteRune(r)
continue mainloop
}
}
if rw := CellCount(string(r)); rw <= w {
w -= rw
buf.WriteRune(r)
} else {
break
}
}
for w > 0 {
buf.WriteByte(' ')
w--
}
return
}
func round(val float64) (newVal float64) {
roundOn := 0.5
places := 0
var round float64
pow := math.Pow(10, float64(places))
digit := pow * val
_, div := math.Modf(digit)
if div >= roundOn {
round = math.Ceil(digit)
} else {
round = math.Floor(digit)
}
newVal = round / pow
return
}
// Convert bytes to human readable string. Like a 2 MiB, 64.2 KiB, 52 B
func formatBytes(i int64) (result string) {
switch {
case i >= _TiB:
result = fmt.Sprintf("%.02f TiB", float64(i)/_TiB)
case i >= _GiB:
result = fmt.Sprintf("%.02f GiB", float64(i)/_GiB)
case i >= _MiB:
result = fmt.Sprintf("%.02f MiB", float64(i)/_MiB)
case i >= _KiB:
result = fmt.Sprintf("%.02f KiB", float64(i)/_KiB)
default:
result = fmt.Sprintf("%d B", i)
}
return
}