You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

encode.go 8.6KB

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