-
Notifications
You must be signed in to change notification settings - Fork 6
/
formatter.go
244 lines (202 loc) · 5.2 KB
/
formatter.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
/* Go IPP - IPP core protocol implementation in pure Go
*
* Copyright (C) 2020 and up by Alexander Pevzner ([email protected])
* See LICENSE for license terms and conditions
*
* IPP formatter (pretty-printer)
*/
package goipp
import (
"bytes"
"fmt"
"io"
"strings"
)
// Formatter parameters:
const (
// FormatterIndentShift is the indentation shift, number of space
// characters per indentation level.
FormatterIndentShift = 4
// FormatterMaxWidth is the maximum text width Formatter attempts to
// achieve.
//
// If text appears to be too wide, Formatter will try to use
// mukti-line output, where possible.
FormatterMaxWidth = 78
)
// Formatter formats IPP messages, attributes, groups etc
// for pretty-printing.
//
// It supersedes [Message.Print] method which is now considered
// deprecated.
type Formatter struct {
indent int // Indentation level
userIndent int // User-settable indent
buf bytes.Buffer // Output buffer
}
// NewFormatter returns a new Formatter
func NewFormatter() *Formatter {
return &Formatter{}
}
// Reset resets the formatter
func (f *Formatter) Reset() {
f.buf.Reset()
f.indent = 0
}
// SetIndent configures indentation. If parameter is greater that
// zero, the specified amount of white space will prepended to each
// non-empty output line.
func (f *Formatter) SetIndent(n int) {
f.userIndent = 0
if n > 0 {
f.userIndent = n
}
}
// Bytes returns formatted text as a byte slice
func (f *Formatter) Bytes() []byte {
return f.buf.Bytes()
}
// String returns formatted text as a string
func (f *Formatter) String() string {
return f.buf.String()
}
// WriteTo writes formatted text to w.
// It implements [io.WriterTo] interface.
func (f *Formatter) WriteTo(w io.Writer) (int64, error) {
return f.buf.WriteTo(w)
}
// Printf writes formatted line into the [Pager], automatically
// indented and with added newline at the end.
//
// It returns the number of bytes written and nil as an error (for
// consistency with other printf-like functions).
func (f *Formatter) Printf(format string, args ...interface{}) (int, error) {
s := fmt.Sprintf(format, args...)
lines := strings.Split(s, "\n")
cnt := 0
for _, line := range lines {
if line != "" {
cnt += f.doIndent()
}
f.buf.WriteString(line)
f.buf.WriteByte('\n')
cnt += len(line) + 1
}
return cnt, nil
}
// FmtRequest formats a request [Message].
func (f *Formatter) FmtRequest(msg *Message) {
f.fmtMessage(msg, true)
}
// FmtResponse formats a response [Message].
func (f *Formatter) FmtResponse(msg *Message) {
f.fmtMessage(msg, false)
}
// fmtMessage formats a request or response Message
func (f *Formatter) fmtMessage(msg *Message, request bool) {
f.Printf("{")
f.indent++
f.Printf("REQUEST-ID %d", msg.RequestID)
f.Printf("VERSION %s", msg.Version)
if request {
f.Printf("OPERATION %s", Op(msg.Code))
} else {
f.Printf("STATUS %s", Status(msg.Code))
}
if groups := msg.attrGroups(); len(groups) != 0 {
f.Printf("")
f.FmtGroups(groups)
}
f.indent--
f.Printf("}")
}
// FmtGroups formats a [Groups] slice.
func (f *Formatter) FmtGroups(groups Groups) {
for i, g := range groups {
if i != 0 {
f.Printf("")
}
f.FmtGroup(g)
}
}
// FmtGroup formats a single [Group].
func (f *Formatter) FmtGroup(g Group) {
f.Printf("GROUP %s", g.Tag)
f.FmtAttributes(g.Attrs)
}
// FmtAttributes formats a [Attributes] slice.
func (f *Formatter) FmtAttributes(attrs Attributes) {
for _, attr := range attrs {
f.FmtAttribute(attr)
}
}
// FmtAttribute formats a single [Attribute].
func (f *Formatter) FmtAttribute(attr Attribute) {
f.fmtAttributeOrMember(attr, false)
}
// FmtAttributes formats a single [Attribute] or collection member
func (f *Formatter) fmtAttributeOrMember(attr Attribute, member bool) {
buf := &f.buf
f.doIndent()
if member {
fmt.Fprintf(buf, "MEMBER %q", attr.Name)
} else {
fmt.Fprintf(buf, "ATTR %q", attr.Name)
}
tag := TagZero
for _, val := range attr.Values {
if val.T != tag {
fmt.Fprintf(buf, " %s:", val.T)
tag = val.T
}
if collection, ok := val.V.(Collection); ok {
if f.onNL() {
f.Printf("{")
} else {
buf.Write([]byte(" {\n"))
}
f.indent++
for _, attr2 := range collection {
f.fmtAttributeOrMember(attr2, true)
}
f.indent--
f.Printf("}")
} else {
fmt.Fprintf(buf, " %s", val.V)
}
}
f.forceNL()
}
// onNL returns true if formatter is at the beginning of new line
func (f *Formatter) onNL() bool {
b := f.buf.Bytes()
return len(b) == 0 || b[len(b)-1] == '\n'
}
// forceNL inserts newline character if formatter is not at the
// beginning of new line
func (f *Formatter) forceNL() {
if !f.onNL() {
f.buf.WriteByte('\n')
}
}
// doIndent outputs indentation space.
// It returns number of characters written.
func (f *Formatter) doIndent() int {
cnt := FormatterIndentShift * f.indent
cnt += f.userIndent
n := cnt
for n > len(formatterSomeSpace) {
f.buf.Write([]byte(formatterSomeSpace[:]))
n -= len(formatterSomeSpace)
}
f.buf.Write([]byte(formatterSomeSpace[:n]))
return cnt
}
// formatterSomeSpace contains some space characters for
// fast output of indentation space.
var formatterSomeSpace [64]byte
func init() {
for i := range formatterSomeSpace {
formatterSomeSpace[i] = ' '
}
}