File tree Expand file tree Collapse file tree 2 files changed +51
-1
lines changed Expand file tree Collapse file tree 2 files changed +51
-1
lines changed Original file line number Diff line number Diff line change @@ -168,6 +168,10 @@ func nonSpace(b []byte) bool {
168168type Encoder struct {
169169w io.Writer
170170err error
171+
172+ indentBuf * bytes.Buffer
173+ indentPrefix string
174+ indentValue string
171175}
172176
173177// NewEncoder returns a new encoder that writes to w.
@@ -198,13 +202,29 @@ func (enc *Encoder) Encode(v interface{}) error {
198202// digits coming.
199203e .WriteByte ('\n' )
200204
201- if _ , err = enc .w .Write (e .Bytes ()); err != nil {
205+ b := e .Bytes ()
206+ if enc .indentBuf != nil {
207+ enc .indentBuf .Reset ()
208+ err = Indent (enc .indentBuf , b , enc .indentPrefix , enc .indentValue )
209+ if err != nil {
210+ return err
211+ }
212+ b = enc .indentBuf .Bytes ()
213+ }
214+ if _ , err = enc .w .Write (b ); err != nil {
202215enc .err = err
203216}
204217encodeStatePool .Put (e )
205218return err
206219}
207220
221+ // Indent sets the encoder to format each encoded object with Indent.
222+ func (enc * Encoder ) Indent (prefix , indent string ) {
223+ enc .indentBuf = new (bytes.Buffer )
224+ enc .indentPrefix = prefix
225+ enc .indentValue = indent
226+ }
227+
208228// RawMessage is a raw encoded JSON object.
209229// It implements Marshaler and Unmarshaler and can
210230// be used to delay JSON decoding or precompute a JSON encoding.
Original file line number Diff line number Diff line change @@ -57,6 +57,36 @@ func TestEncoder(t *testing.T) {
5757}
5858}
5959
60+ var streamEncodedIndent = `0.1
61+ "hello"
62+ null
63+ true
64+ false
65+ [
66+ >."a",
67+ >."b",
68+ >."c"
69+ >]
70+ {
71+ >."ß": "long s",
72+ >."K": "Kelvin"
73+ >}
74+ 3.14
75+ `
76+
77+ func TestEncoderIndent (t * testing.T ) {
78+ var buf bytes.Buffer
79+ enc := NewEncoder (& buf )
80+ enc .Indent (">" , "." )
81+ for _ , v := range streamTest {
82+ enc .Encode (v )
83+ }
84+ if have , want := buf .String (), streamEncodedIndent ; have != want {
85+ t .Error ("indented encoding mismatch" )
86+ diff (t , []byte (have ), []byte (want ))
87+ }
88+ }
89+
6090func TestDecoder (t * testing.T ) {
6191for i := 0 ; i <= len (streamTest ); i ++ {
6292// Use stream without newlines as input,
You can’t perform that action at this time.
0 commit comments