stream.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. out := newBytes()
  35. /* encode into the buffer */
  36. err = EncodeInto(&out, val, enc.Opts)
  37. if err != nil {
  38. goto free_bytes
  39. }
  40. if enc.indent != "" || enc.prefix != "" {
  41. /* indent the JSON */
  42. buf := newBuffer()
  43. err = json.Indent(buf, out, enc.prefix, enc.indent)
  44. if err != nil {
  45. freeBuffer(buf)
  46. goto free_bytes
  47. }
  48. // according to standard library, terminate each value with a newline...
  49. buf.WriteByte('\n')
  50. /* copy into io.Writer */
  51. _, err = io.Copy(enc.w, buf)
  52. if err != nil {
  53. freeBuffer(buf)
  54. goto free_bytes
  55. }
  56. } else {
  57. /* copy into io.Writer */
  58. var n int
  59. for len(out) > 0 {
  60. n, err = enc.w.Write(out)
  61. out = out[n:]
  62. if err != nil {
  63. goto free_bytes
  64. }
  65. }
  66. // according to standard library, terminate each value with a newline...
  67. enc.w.Write([]byte{'\n'})
  68. }
  69. free_bytes:
  70. freeBytes(out)
  71. return err
  72. }