...
1
16
17 package util
18
19 import (
20 "bytes"
21 "fmt"
22 )
23
24
25 type LineBuffer interface {
26
27
28
29 Write(args ...interface{})
30
31
32 WriteBytes(bytes []byte)
33
34
35 Reset()
36
37
38 Bytes() []byte
39
40
41 String() string
42
43
44
45
46 Lines() int
47 }
48
49 type realLineBuffer struct {
50 b bytes.Buffer
51 lines int
52 }
53
54
55 func NewLineBuffer() LineBuffer {
56 return &realLineBuffer{}
57 }
58
59
60 func (buf *realLineBuffer) Write(args ...interface{}) {
61 for i, arg := range args {
62 if i > 0 {
63 buf.b.WriteByte(' ')
64 }
65 switch x := arg.(type) {
66 case string:
67 buf.b.WriteString(x)
68 case []string:
69 for j, s := range x {
70 if j > 0 {
71 buf.b.WriteByte(' ')
72 }
73 buf.b.WriteString(s)
74 }
75 default:
76 panic(fmt.Sprintf("unknown argument type: %T", x))
77 }
78 }
79 buf.b.WriteByte('\n')
80 buf.lines++
81 }
82
83
84 func (buf *realLineBuffer) WriteBytes(bytes []byte) {
85 buf.b.Write(bytes)
86 buf.b.WriteByte('\n')
87 buf.lines++
88 }
89
90
91 func (buf *realLineBuffer) Reset() {
92 buf.b.Reset()
93 buf.lines = 0
94 }
95
96
97 func (buf *realLineBuffer) Bytes() []byte {
98 return buf.b.Bytes()
99 }
100
101
102 func (buf *realLineBuffer) String() string {
103 return buf.b.String()
104 }
105
106
107 func (buf *realLineBuffer) Lines() int {
108 return buf.lines
109 }
110
111 type discardLineBuffer struct {
112 lines int
113 }
114
115
116
117
118 func NewDiscardLineBuffer() LineBuffer {
119 return &discardLineBuffer{}
120 }
121
122
123 func (buf *discardLineBuffer) Write(args ...interface{}) {
124 buf.lines++
125 }
126
127
128 func (buf *discardLineBuffer) WriteBytes(bytes []byte) {
129 buf.lines++
130 }
131
132
133 func (buf *discardLineBuffer) Reset() {
134 buf.lines = 0
135 }
136
137
138 func (buf *discardLineBuffer) Bytes() []byte {
139 return []byte{}
140 }
141
142
143 func (buf *discardLineBuffer) String() string {
144 return ""
145 }
146
147
148 func (buf *discardLineBuffer) Lines() int {
149 return buf.lines
150 }
151
View as plain text