stream.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. * Copyright 2021 ByteDance Inc.
  3. *
  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
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  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.
  15. */
  16. package encoder
  17. import (
  18. `encoding/json`
  19. `io`
  20. )
  21. // StreamEncoder uses io.Writer as input.
  22. type StreamEncoder struct {
  23. w io.Writer
  24. Encoder
  25. }
  26. // NewStreamEncoder adapts to encoding/json.NewDecoder API.
  27. //
  28. // NewStreamEncoder returns a new encoder that write to w.
  29. func NewStreamEncoder(w io.Writer) *StreamEncoder {
  30. return &StreamEncoder{w: w}
  31. }
  32. // Encode encodes interface{} as JSON to io.Writer
  33. func (enc *StreamEncoder) Encode(val interface{}) (err error) {
  34. buf := newBytes()
  35. out := buf
  36. /* encode into the buffer */
  37. err = EncodeInto(&out, val, enc.Opts)
  38. if err != nil {
  39. goto free_bytes
  40. }
  41. if enc.indent != "" || enc.prefix != "" {
  42. /* indent the JSON */
  43. buf := newBuffer()
  44. err = json.Indent(buf, out, enc.prefix, enc.indent)
  45. if err != nil {
  46. freeBuffer(buf)
  47. goto free_bytes
  48. }
  49. // according to standard library, terminate each value with a newline...
  50. if enc.Opts & NoEncoderNewline == 0 {
  51. buf.WriteByte('\n')
  52. }
  53. /* copy into io.Writer */
  54. _, err = io.Copy(enc.w, buf)
  55. if err != nil {
  56. freeBuffer(buf)
  57. goto free_bytes
  58. }
  59. } else {
  60. /* copy into io.Writer */
  61. var n int
  62. for len(out) > 0 {
  63. n, err = enc.w.Write(out)
  64. out = out[n:]
  65. if err != nil {
  66. goto free_bytes
  67. }
  68. }
  69. // according to standard library, terminate each value with a newline...
  70. if enc.Opts & NoEncoderNewline == 0 {
  71. enc.w.Write([]byte{'\n'})
  72. }
  73. }
  74. free_bytes:
  75. freeBytes(buf)
  76. return err
  77. }