encode.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. package json
  2. import (
  3. "context"
  4. "io"
  5. "os"
  6. "unsafe"
  7. "github.com/goccy/go-json/internal/encoder"
  8. "github.com/goccy/go-json/internal/encoder/vm"
  9. "github.com/goccy/go-json/internal/encoder/vm_color"
  10. "github.com/goccy/go-json/internal/encoder/vm_color_indent"
  11. "github.com/goccy/go-json/internal/encoder/vm_indent"
  12. )
  13. // An Encoder writes JSON values to an output stream.
  14. type Encoder struct {
  15. w io.Writer
  16. enabledIndent bool
  17. enabledHTMLEscape bool
  18. prefix string
  19. indentStr string
  20. }
  21. // NewEncoder returns a new encoder that writes to w.
  22. func NewEncoder(w io.Writer) *Encoder {
  23. return &Encoder{w: w, enabledHTMLEscape: true}
  24. }
  25. // Encode writes the JSON encoding of v to the stream, followed by a newline character.
  26. //
  27. // See the documentation for Marshal for details about the conversion of Go values to JSON.
  28. func (e *Encoder) Encode(v interface{}) error {
  29. return e.EncodeWithOption(v)
  30. }
  31. // EncodeWithOption call Encode with EncodeOption.
  32. func (e *Encoder) EncodeWithOption(v interface{}, optFuncs ...EncodeOptionFunc) error {
  33. ctx := encoder.TakeRuntimeContext()
  34. ctx.Option.Flag = 0
  35. err := e.encodeWithOption(ctx, v, optFuncs...)
  36. encoder.ReleaseRuntimeContext(ctx)
  37. return err
  38. }
  39. // EncodeContext call Encode with context.Context and EncodeOption.
  40. func (e *Encoder) EncodeContext(ctx context.Context, v interface{}, optFuncs ...EncodeOptionFunc) error {
  41. rctx := encoder.TakeRuntimeContext()
  42. rctx.Option.Flag = 0
  43. rctx.Option.Flag |= encoder.ContextOption
  44. rctx.Option.Context = ctx
  45. err := e.encodeWithOption(rctx, v, optFuncs...)
  46. encoder.ReleaseRuntimeContext(rctx)
  47. return err
  48. }
  49. func (e *Encoder) encodeWithOption(ctx *encoder.RuntimeContext, v interface{}, optFuncs ...EncodeOptionFunc) error {
  50. if e.enabledHTMLEscape {
  51. ctx.Option.Flag |= encoder.HTMLEscapeOption
  52. }
  53. ctx.Option.Flag |= encoder.NormalizeUTF8Option
  54. ctx.Option.DebugOut = os.Stdout
  55. for _, optFunc := range optFuncs {
  56. optFunc(ctx.Option)
  57. }
  58. var (
  59. buf []byte
  60. err error
  61. )
  62. if e.enabledIndent {
  63. buf, err = encodeIndent(ctx, v, e.prefix, e.indentStr)
  64. } else {
  65. buf, err = encode(ctx, v)
  66. }
  67. if err != nil {
  68. return err
  69. }
  70. if e.enabledIndent {
  71. buf = buf[:len(buf)-2]
  72. } else {
  73. buf = buf[:len(buf)-1]
  74. }
  75. buf = append(buf, '\n')
  76. if _, err := e.w.Write(buf); err != nil {
  77. return err
  78. }
  79. return nil
  80. }
  81. // SetEscapeHTML specifies whether problematic HTML characters should be escaped inside JSON quoted strings.
  82. // The default behavior is to escape &, <, and > to \u0026, \u003c, and \u003e to avoid certain safety problems that can arise when embedding JSON in HTML.
  83. //
  84. // In non-HTML settings where the escaping interferes with the readability of the output, SetEscapeHTML(false) disables this behavior.
  85. func (e *Encoder) SetEscapeHTML(on bool) {
  86. e.enabledHTMLEscape = on
  87. }
  88. // SetIndent instructs the encoder to format each subsequent encoded value as if indented by the package-level function Indent(dst, src, prefix, indent).
  89. // Calling SetIndent("", "") disables indentation.
  90. func (e *Encoder) SetIndent(prefix, indent string) {
  91. if prefix == "" && indent == "" {
  92. e.enabledIndent = false
  93. return
  94. }
  95. e.prefix = prefix
  96. e.indentStr = indent
  97. e.enabledIndent = true
  98. }
  99. func marshalContext(ctx context.Context, v interface{}, optFuncs ...EncodeOptionFunc) ([]byte, error) {
  100. rctx := encoder.TakeRuntimeContext()
  101. rctx.Option.Flag = 0
  102. rctx.Option.Flag = encoder.HTMLEscapeOption | encoder.NormalizeUTF8Option | encoder.ContextOption
  103. rctx.Option.Context = ctx
  104. for _, optFunc := range optFuncs {
  105. optFunc(rctx.Option)
  106. }
  107. buf, err := encode(rctx, v)
  108. if err != nil {
  109. encoder.ReleaseRuntimeContext(rctx)
  110. return nil, err
  111. }
  112. // this line exists to escape call of `runtime.makeslicecopy` .
  113. // if use `make([]byte, len(buf)-1)` and `copy(copied, buf)`,
  114. // dst buffer size and src buffer size are differrent.
  115. // in this case, compiler uses `runtime.makeslicecopy`, but it is slow.
  116. buf = buf[:len(buf)-1]
  117. copied := make([]byte, len(buf))
  118. copy(copied, buf)
  119. encoder.ReleaseRuntimeContext(rctx)
  120. return copied, nil
  121. }
  122. func marshal(v interface{}, optFuncs ...EncodeOptionFunc) ([]byte, error) {
  123. ctx := encoder.TakeRuntimeContext()
  124. ctx.Option.Flag = 0
  125. ctx.Option.Flag |= (encoder.HTMLEscapeOption | encoder.NormalizeUTF8Option)
  126. for _, optFunc := range optFuncs {
  127. optFunc(ctx.Option)
  128. }
  129. buf, err := encode(ctx, v)
  130. if err != nil {
  131. encoder.ReleaseRuntimeContext(ctx)
  132. return nil, err
  133. }
  134. // this line exists to escape call of `runtime.makeslicecopy` .
  135. // if use `make([]byte, len(buf)-1)` and `copy(copied, buf)`,
  136. // dst buffer size and src buffer size are differrent.
  137. // in this case, compiler uses `runtime.makeslicecopy`, but it is slow.
  138. buf = buf[:len(buf)-1]
  139. copied := make([]byte, len(buf))
  140. copy(copied, buf)
  141. encoder.ReleaseRuntimeContext(ctx)
  142. return copied, nil
  143. }
  144. func marshalNoEscape(v interface{}) ([]byte, error) {
  145. ctx := encoder.TakeRuntimeContext()
  146. ctx.Option.Flag = 0
  147. ctx.Option.Flag |= (encoder.HTMLEscapeOption | encoder.NormalizeUTF8Option)
  148. buf, err := encodeNoEscape(ctx, v)
  149. if err != nil {
  150. encoder.ReleaseRuntimeContext(ctx)
  151. return nil, err
  152. }
  153. // this line exists to escape call of `runtime.makeslicecopy` .
  154. // if use `make([]byte, len(buf)-1)` and `copy(copied, buf)`,
  155. // dst buffer size and src buffer size are differrent.
  156. // in this case, compiler uses `runtime.makeslicecopy`, but it is slow.
  157. buf = buf[:len(buf)-1]
  158. copied := make([]byte, len(buf))
  159. copy(copied, buf)
  160. encoder.ReleaseRuntimeContext(ctx)
  161. return copied, nil
  162. }
  163. func marshalIndent(v interface{}, prefix, indent string, optFuncs ...EncodeOptionFunc) ([]byte, error) {
  164. ctx := encoder.TakeRuntimeContext()
  165. ctx.Option.Flag = 0
  166. ctx.Option.Flag |= (encoder.HTMLEscapeOption | encoder.NormalizeUTF8Option | encoder.IndentOption)
  167. for _, optFunc := range optFuncs {
  168. optFunc(ctx.Option)
  169. }
  170. buf, err := encodeIndent(ctx, v, prefix, indent)
  171. if err != nil {
  172. encoder.ReleaseRuntimeContext(ctx)
  173. return nil, err
  174. }
  175. buf = buf[:len(buf)-2]
  176. copied := make([]byte, len(buf))
  177. copy(copied, buf)
  178. encoder.ReleaseRuntimeContext(ctx)
  179. return copied, nil
  180. }
  181. func encode(ctx *encoder.RuntimeContext, v interface{}) ([]byte, error) {
  182. b := ctx.Buf[:0]
  183. if v == nil {
  184. b = encoder.AppendNull(ctx, b)
  185. b = encoder.AppendComma(ctx, b)
  186. return b, nil
  187. }
  188. header := (*emptyInterface)(unsafe.Pointer(&v))
  189. typ := header.typ
  190. typeptr := uintptr(unsafe.Pointer(typ))
  191. codeSet, err := encoder.CompileToGetCodeSet(ctx, typeptr)
  192. if err != nil {
  193. return nil, err
  194. }
  195. p := uintptr(header.ptr)
  196. ctx.Init(p, codeSet.CodeLength)
  197. ctx.KeepRefs = append(ctx.KeepRefs, header.ptr)
  198. buf, err := encodeRunCode(ctx, b, codeSet)
  199. if err != nil {
  200. return nil, err
  201. }
  202. ctx.Buf = buf
  203. return buf, nil
  204. }
  205. func encodeNoEscape(ctx *encoder.RuntimeContext, v interface{}) ([]byte, error) {
  206. b := ctx.Buf[:0]
  207. if v == nil {
  208. b = encoder.AppendNull(ctx, b)
  209. b = encoder.AppendComma(ctx, b)
  210. return b, nil
  211. }
  212. header := (*emptyInterface)(unsafe.Pointer(&v))
  213. typ := header.typ
  214. typeptr := uintptr(unsafe.Pointer(typ))
  215. codeSet, err := encoder.CompileToGetCodeSet(ctx, typeptr)
  216. if err != nil {
  217. return nil, err
  218. }
  219. p := uintptr(header.ptr)
  220. ctx.Init(p, codeSet.CodeLength)
  221. buf, err := encodeRunCode(ctx, b, codeSet)
  222. if err != nil {
  223. return nil, err
  224. }
  225. ctx.Buf = buf
  226. return buf, nil
  227. }
  228. func encodeIndent(ctx *encoder.RuntimeContext, v interface{}, prefix, indent string) ([]byte, error) {
  229. b := ctx.Buf[:0]
  230. if v == nil {
  231. b = encoder.AppendNull(ctx, b)
  232. b = encoder.AppendCommaIndent(ctx, b)
  233. return b, nil
  234. }
  235. header := (*emptyInterface)(unsafe.Pointer(&v))
  236. typ := header.typ
  237. typeptr := uintptr(unsafe.Pointer(typ))
  238. codeSet, err := encoder.CompileToGetCodeSet(ctx, typeptr)
  239. if err != nil {
  240. return nil, err
  241. }
  242. p := uintptr(header.ptr)
  243. ctx.Init(p, codeSet.CodeLength)
  244. buf, err := encodeRunIndentCode(ctx, b, codeSet, prefix, indent)
  245. ctx.KeepRefs = append(ctx.KeepRefs, header.ptr)
  246. if err != nil {
  247. return nil, err
  248. }
  249. ctx.Buf = buf
  250. return buf, nil
  251. }
  252. func encodeRunCode(ctx *encoder.RuntimeContext, b []byte, codeSet *encoder.OpcodeSet) ([]byte, error) {
  253. if (ctx.Option.Flag & encoder.DebugOption) != 0 {
  254. if (ctx.Option.Flag & encoder.ColorizeOption) != 0 {
  255. return vm_color.DebugRun(ctx, b, codeSet)
  256. }
  257. return vm.DebugRun(ctx, b, codeSet)
  258. }
  259. if (ctx.Option.Flag & encoder.ColorizeOption) != 0 {
  260. return vm_color.Run(ctx, b, codeSet)
  261. }
  262. return vm.Run(ctx, b, codeSet)
  263. }
  264. func encodeRunIndentCode(ctx *encoder.RuntimeContext, b []byte, codeSet *encoder.OpcodeSet, prefix, indent string) ([]byte, error) {
  265. ctx.Prefix = []byte(prefix)
  266. ctx.IndentStr = []byte(indent)
  267. if (ctx.Option.Flag & encoder.DebugOption) != 0 {
  268. if (ctx.Option.Flag & encoder.ColorizeOption) != 0 {
  269. return vm_color_indent.DebugRun(ctx, b, codeSet)
  270. }
  271. return vm_indent.DebugRun(ctx, b, codeSet)
  272. }
  273. if (ctx.Option.Flag & encoder.ColorizeOption) != 0 {
  274. return vm_color_indent.Run(ctx, b, codeSet)
  275. }
  276. return vm_indent.Run(ctx, b, codeSet)
  277. }