options.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. // Copyright 2023 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package jsontext
  5. import (
  6. "strings"
  7. "github.com/go-json-experiment/json/internal/jsonflags"
  8. "github.com/go-json-experiment/json/internal/jsonopts"
  9. "github.com/go-json-experiment/json/internal/jsonwire"
  10. )
  11. // Options configures [NewEncoder], [Encoder.Reset], [NewDecoder],
  12. // and [Decoder.Reset] with specific features.
  13. // Each function takes in a variadic list of options, where properties
  14. // set in latter options override the value of previously set properties.
  15. //
  16. // There is a single Options type, which is used with both encoding and decoding.
  17. // Some options affect both operations, while others only affect one operation:
  18. //
  19. // - [AllowDuplicateNames] affects encoding and decoding
  20. // - [AllowInvalidUTF8] affects encoding and decoding
  21. // - [EscapeForHTML] affects encoding only
  22. // - [EscapeForJS] affects encoding only
  23. // - [PreserveRawStrings] affects encoding only
  24. // - [CanonicalizeRawInts] affects encoding only
  25. // - [CanonicalizeRawFloats] affects encoding only
  26. // - [ReorderRawObjects] affects encoding only
  27. // - [SpaceAfterColon] affects encoding only
  28. // - [SpaceAfterComma] affects encoding only
  29. // - [Multiline] affects encoding only
  30. // - [WithIndent] affects encoding only
  31. // - [WithIndentPrefix] affects encoding only
  32. //
  33. // Options that do not affect a particular operation are ignored.
  34. //
  35. // The Options type is identical to [encoding/json.Options] and
  36. // [encoding/json/v2.Options]. Options from the other packages may
  37. // be passed to functionality in this package, but are ignored.
  38. // Options from this package may be used with the other packages.
  39. type Options = jsonopts.Options
  40. // AllowDuplicateNames specifies that JSON objects may contain
  41. // duplicate member names. Disabling the duplicate name check may provide
  42. // performance benefits, but breaks compliance with RFC 7493, section 2.3.
  43. // The input or output will still be compliant with RFC 8259,
  44. // which leaves the handling of duplicate names as unspecified behavior.
  45. //
  46. // This affects either encoding or decoding.
  47. func AllowDuplicateNames(v bool) Options {
  48. if v {
  49. return jsonflags.AllowDuplicateNames | 1
  50. } else {
  51. return jsonflags.AllowDuplicateNames | 0
  52. }
  53. }
  54. // AllowInvalidUTF8 specifies that JSON strings may contain invalid UTF-8,
  55. // which will be mangled as the Unicode replacement character, U+FFFD.
  56. // This causes the encoder or decoder to break compliance with
  57. // RFC 7493, section 2.1, and RFC 8259, section 8.1.
  58. //
  59. // This affects either encoding or decoding.
  60. func AllowInvalidUTF8(v bool) Options {
  61. if v {
  62. return jsonflags.AllowInvalidUTF8 | 1
  63. } else {
  64. return jsonflags.AllowInvalidUTF8 | 0
  65. }
  66. }
  67. // EscapeForHTML specifies that '<', '>', and '&' characters within JSON strings
  68. // should be escaped as a hexadecimal Unicode codepoint (e.g., \u003c) so that
  69. // the output is safe to embed within HTML.
  70. //
  71. // This only affects encoding and is ignored when decoding.
  72. func EscapeForHTML(v bool) Options {
  73. if v {
  74. return jsonflags.EscapeForHTML | 1
  75. } else {
  76. return jsonflags.EscapeForHTML | 0
  77. }
  78. }
  79. // EscapeForJS specifies that U+2028 and U+2029 characters within JSON strings
  80. // should be escaped as a hexadecimal Unicode codepoint (e.g., \u2028) so that
  81. // the output is valid to embed within JavaScript. See RFC 8259, section 12.
  82. //
  83. // This only affects encoding and is ignored when decoding.
  84. func EscapeForJS(v bool) Options {
  85. if v {
  86. return jsonflags.EscapeForJS | 1
  87. } else {
  88. return jsonflags.EscapeForJS | 0
  89. }
  90. }
  91. // PreserveRawStrings specifies that when encoding a raw JSON string in a
  92. // [Token] or [Value], pre-escaped sequences
  93. // in a JSON string are preserved to the output.
  94. // However, raw strings still respect [EscapeForHTML] and [EscapeForJS]
  95. // such that the relevant characters are escaped.
  96. // If [AllowInvalidUTF8] is enabled, bytes of invalid UTF-8
  97. // are preserved to the output.
  98. //
  99. // This only affects encoding and is ignored when decoding.
  100. func PreserveRawStrings(v bool) Options {
  101. if v {
  102. return jsonflags.PreserveRawStrings | 1
  103. } else {
  104. return jsonflags.PreserveRawStrings | 0
  105. }
  106. }
  107. // CanonicalizeRawInts specifies that when encoding a raw JSON
  108. // integer number (i.e., a number without a fraction and exponent) in a
  109. // [Token] or [Value], the number is canonicalized
  110. // according to RFC 8785, section 3.2.2.3. As a special case,
  111. // the number -0 is canonicalized as 0.
  112. //
  113. // JSON numbers are treated as IEEE 754 double precision numbers.
  114. // Any numbers with precision beyond what is representable by that form
  115. // will lose their precision when canonicalized. For example,
  116. // integer values beyond ±2⁵³ will lose their precision.
  117. // For example, 1234567890123456789 is formatted as 1234567890123456800.
  118. //
  119. // This only affects encoding and is ignored when decoding.
  120. func CanonicalizeRawInts(v bool) Options {
  121. if v {
  122. return jsonflags.CanonicalizeRawInts | 1
  123. } else {
  124. return jsonflags.CanonicalizeRawInts | 0
  125. }
  126. }
  127. // CanonicalizeRawFloats specifies that when encoding a raw JSON
  128. // floating-point number (i.e., a number with a fraction or exponent) in a
  129. // [Token] or [Value], the number is canonicalized
  130. // according to RFC 8785, section 3.2.2.3. As a special case,
  131. // the number -0 is canonicalized as 0.
  132. //
  133. // JSON numbers are treated as IEEE 754 double precision numbers.
  134. // It is safe to canonicalize a serialized single precision number and
  135. // parse it back as a single precision number and expect the same value.
  136. // If a number exceeds ±1.7976931348623157e+308, which is the maximum
  137. // finite number, then it saturated at that value and formatted as such.
  138. //
  139. // This only affects encoding and is ignored when decoding.
  140. func CanonicalizeRawFloats(v bool) Options {
  141. if v {
  142. return jsonflags.CanonicalizeRawFloats | 1
  143. } else {
  144. return jsonflags.CanonicalizeRawFloats | 0
  145. }
  146. }
  147. // ReorderRawObjects specifies that when encoding a raw JSON object in a
  148. // [Value], the object members are reordered according to
  149. // RFC 8785, section 3.2.3.
  150. //
  151. // This only affects encoding and is ignored when decoding.
  152. func ReorderRawObjects(v bool) Options {
  153. if v {
  154. return jsonflags.ReorderRawObjects | 1
  155. } else {
  156. return jsonflags.ReorderRawObjects | 0
  157. }
  158. }
  159. // SpaceAfterColon specifies that the JSON output should emit a space character
  160. // after each colon separator following a JSON object name.
  161. // If false, then no space character appears after the colon separator.
  162. //
  163. // This only affects encoding and is ignored when decoding.
  164. func SpaceAfterColon(v bool) Options {
  165. if v {
  166. return jsonflags.SpaceAfterColon | 1
  167. } else {
  168. return jsonflags.SpaceAfterColon | 0
  169. }
  170. }
  171. // SpaceAfterComma specifies that the JSON output should emit a space character
  172. // after each comma separator following a JSON object value or array element.
  173. // If false, then no space character appears after the comma separator.
  174. //
  175. // This only affects encoding and is ignored when decoding.
  176. func SpaceAfterComma(v bool) Options {
  177. if v {
  178. return jsonflags.SpaceAfterComma | 1
  179. } else {
  180. return jsonflags.SpaceAfterComma | 0
  181. }
  182. }
  183. // Multiline specifies that the JSON output should expand to multiple lines,
  184. // where every JSON object member or JSON array element appears on
  185. // a new, indented line according to the nesting depth.
  186. //
  187. // If [SpaceAfterColon] is not specified, then the default is true.
  188. // If [SpaceAfterComma] is not specified, then the default is false.
  189. // If [WithIndent] is not specified, then the default is "\t".
  190. //
  191. // If set to false, then the output is a single-line,
  192. // where the only whitespace emitted is determined by the current
  193. // values of [SpaceAfterColon] and [SpaceAfterComma].
  194. //
  195. // This only affects encoding and is ignored when decoding.
  196. func Multiline(v bool) Options {
  197. if v {
  198. return jsonflags.Multiline | 1
  199. } else {
  200. return jsonflags.Multiline | 0
  201. }
  202. }
  203. // WithIndent specifies that the encoder should emit multiline output
  204. // where each element in a JSON object or array begins on a new, indented line
  205. // beginning with the indent prefix (see [WithIndentPrefix])
  206. // followed by one or more copies of indent according to the nesting depth.
  207. // The indent must only be composed of space or tab characters.
  208. //
  209. // If the intent to emit indented output without a preference for
  210. // the particular indent string, then use [Multiline] instead.
  211. //
  212. // This only affects encoding and is ignored when decoding.
  213. // Use of this option implies [Multiline] being set to true.
  214. func WithIndent(indent string) Options {
  215. // Fast-path: Return a constant for common indents, which avoids allocating.
  216. // These are derived from analyzing the Go module proxy on 2023-07-01.
  217. switch indent {
  218. case "\t":
  219. return jsonopts.Indent("\t") // ~14k usages
  220. case " ":
  221. return jsonopts.Indent(" ") // ~18k usages
  222. case " ":
  223. return jsonopts.Indent(" ") // ~1.7k usages
  224. case " ":
  225. return jsonopts.Indent(" ") // ~52k usages
  226. case " ":
  227. return jsonopts.Indent(" ") // ~12k usages
  228. case "":
  229. return jsonopts.Indent("") // ~1.5k usages
  230. }
  231. // Otherwise, allocate for this unique value.
  232. if s := strings.Trim(indent, " \t"); len(s) > 0 {
  233. panic("json: invalid character " + jsonwire.QuoteRune(s) + " in indent")
  234. }
  235. return jsonopts.Indent(indent)
  236. }
  237. // WithIndentPrefix specifies that the encoder should emit multiline output
  238. // where each element in a JSON object or array begins on a new, indented line
  239. // beginning with the indent prefix followed by one or more copies of indent
  240. // (see [WithIndent]) according to the nesting depth.
  241. // The prefix must only be composed of space or tab characters.
  242. //
  243. // This only affects encoding and is ignored when decoding.
  244. // Use of this option implies [Multiline] being set to true.
  245. func WithIndentPrefix(prefix string) Options {
  246. if s := strings.Trim(prefix, " \t"); len(s) > 0 {
  247. panic("json: invalid character " + jsonwire.QuoteRune(s) + " in indent prefix")
  248. }
  249. return jsonopts.IndentPrefix(prefix)
  250. }
  251. /*
  252. // TODO(https://go.dev/issue/56733): Implement WithByteLimit and WithDepthLimit.
  253. // WithByteLimit sets a limit on the number of bytes of input or output bytes
  254. // that may be consumed or produced for each top-level JSON value.
  255. // If a [Decoder] or [Encoder] method call would need to consume/produce
  256. // more than a total of n bytes to make progress on the top-level JSON value,
  257. // then the call will report an error.
  258. // Whitespace before and within the top-level value are counted against the limit.
  259. // Whitespace after a top-level value are counted against the limit
  260. // for the next top-level value.
  261. //
  262. // A non-positive limit is equivalent to no limit at all.
  263. // If unspecified, the default limit is no limit at all.
  264. // This affects either encoding or decoding.
  265. func WithByteLimit(n int64) Options {
  266. return jsonopts.ByteLimit(max(n, 0))
  267. }
  268. // WithDepthLimit sets a limit on the maximum depth of JSON nesting
  269. // that may be consumed or produced for each top-level JSON value.
  270. // If a [Decoder] or [Encoder] method call would need to consume or produce
  271. // a depth greater than n to make progress on the top-level JSON value,
  272. // then the call will report an error.
  273. //
  274. // A non-positive limit is equivalent to no limit at all.
  275. // If unspecified, the default limit is 10000.
  276. // This affects either encoding or decoding.
  277. func WithDepthLimit(n int) Options {
  278. return jsonopts.DepthLimit(max(n, 0))
  279. }
  280. */