-
Notifications
You must be signed in to change notification settings - Fork 0
/
fieldwriter.go
55 lines (48 loc) · 1.49 KB
/
fieldwriter.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
package astconf
// fieldWriter is an io.Writer that wraps an Encoder. It will write the
// field name ahead of any field value written via fieldWriter.Write. The
// field name to be written will be pulled from the encoder's scratch data,
// which should have been prepared by a corresponding setting or object
// encoder.
//
// When a fieldEncoder is marshaling a particular field, it creates an
// ephemeral fieldWriter which is then passed to the field's type encoder,
// which may be a custom marshaler implementation.
//
// The first time fieldWriter.Write is called, it writes the field's
// indentation, name and field separator (typically = or =>). If Write is
// never called, the field name information is not written. This design
// allows custom type marshalers to omit a field simply by not writing a
// value for it.
type fieldWriter struct {
*Encoder
}
// Write will write field value p to the underlying writer.
func (fw fieldWriter) Write(p []byte) (n int, err error) {
e := fw.Encoder
s := &e.scratch
if s.started {
return e.w.Write(p)
}
// fw == e.w at this point, so don't use e.w here or we'll loop forever
printer := Printer{
Writer: e.base,
Indent: e.indent,
Alignment: e.alignment,
Started: e.started,
}
if err := printer.start(s.name, s.sep); err != nil {
return 0, err
}
s.started = true
e.w = e.base
return e.w.Write(p)
}
func (fw *fieldWriter) done() error {
e := fw.Encoder
if e.scratch.started {
_, err := e.w.Write(newline)
return err
}
return nil
}