/
colwriter.go
69 lines (53 loc) · 953 Bytes
/
colwriter.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
package main
import "io"
type ColCfg struct {
Wid int
Rt bool
}
type ColWriterCfg struct {
Spacer []byte
Pad bool
}
type ColWriter struct {
buf []byte
}
func (cw *ColWriter) WriteCols(
out io.Writer,
wriCfg ColWriterCfg,
colCfg []ColCfg,
sTxt ...[]byte,
) error {
// reset line buffer
if cw.buf == nil {
cw.buf = make([]byte, 0, 80)
} else {
cw.buf = cw.buf[:0]
}
nLastCol := len(sTxt) - 1
for ix, col := range colCfg {
if ix >= len(sTxt) {
break
}
txt := sTxt[ix]
pad := col.Wid - len(txt)
if !col.Rt {
cw.buf = append(cw.buf, txt...)
}
// padding
if wriCfg.Pad {
for i := pad; i > 0; i -= 1 {
cw.buf = append(cw.buf, ' ')
}
}
if col.Rt {
cw.buf = append(cw.buf, txt...)
}
// column separator
if (len(wriCfg.Spacer) > 0) && (ix < nLastCol) {
cw.buf = append(cw.buf, wriCfg.Spacer...)
}
}
cw.buf = append(cw.buf, '\n')
_, err := out.Write(cw.buf)
return err
}