2
* Copyright 2021 ByteDance Inc.
4
* Licensed under the Apache License, Version 2.0 (the "License");
5
* you may not use this file except in compliance with the License.
6
* You may obtain a copy of the License at
8
* http://www.apache.org/licenses/LICENSE-2.0
10
* Unless required by applicable law or agreed to in writing, software
11
* distributed under the License is distributed on an "AS IS" BASIS,
12
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
* See the License for the specific language governing permissions and
14
* limitations under the License.
24
// StreamEncoder uses io.Writer as input.
25
type StreamEncoder struct {
30
// NewStreamEncoder adapts to encoding/json.NewDecoder API.
32
// NewStreamEncoder returns a new encoder that write to w.
33
func NewStreamEncoder(w io.Writer) *StreamEncoder {
34
return &StreamEncoder{w: w}
37
// Encode encodes interface{} as JSON to io.Writer
38
func (enc *StreamEncoder) Encode(val interface{}) (err error) {
41
/* encode into the buffer */
42
err = EncodeInto(&out, val, enc.Opts)
47
if enc.indent != "" || enc.prefix != "" {
50
err = json.Indent(buf, out, enc.prefix, enc.indent)
56
// according to standard library, terminate each value with a newline...
59
/* copy into io.Writer */
60
_, err = io.Copy(enc.w, buf)
67
/* copy into io.Writer */
70
n, err = enc.w.Write(out)
77
// according to standard library, terminate each value with a newline...
78
enc.w.Write([]byte{'\n'})