// Copyright 2023 The Go Authors. All rights reserved.// Use of this source code is governed by a BSD-style// license that can be found in the LICENSE file.//go:build goexperiment.jsonv2package jsonwireimport ()// escapeASCII reports whether the ASCII character needs to be escaped.// It conservatively assumes EscapeForHTML.var escapeASCII = [...]uint8{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // escape control characters1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // escape control characters0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, // escape '"' and '&'0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, // escape '<' and '>'0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, // escape '\\'0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,}// NeedEscape reports whether src needs escaping of any characters.// It conservatively assumes EscapeForHTML and EscapeForJS.// It reports true for inputs with invalid UTF-8.func [ ~[]byte | ~string]( ) bool {varintforuint(len()) > uint() {if := []; < utf8.RuneSelf {ifescapeASCII[] > 0 {returntrue } ++ } else { , := utf8.DecodeRuneInString(string(truncateMaxUTF8([:])))if == utf8.RuneError || == '\u2028' || == '\u2029' {returntrue } += } }returnfalse}// AppendQuote appends src to dst as a JSON string per RFC 7159, section 7.//// It takes in flags and respects the following:// - EscapeForHTML escapes '<', '>', and '&'.// - EscapeForJS escapes '\u2028' and '\u2029'.// - AllowInvalidUTF8 avoids reporting an error for invalid UTF-8.//// Regardless of whether AllowInvalidUTF8 is specified,// invalid bytes are replaced with the Unicode replacement character ('\ufffd').// If no escape flags are set, then the shortest representable form is used,// which is also the canonical form for strings (RFC 8785, section 3.2.2.2).func [ ~[]byte | ~string]( []byte, , *jsonflags.Flags) ([]byte, error) {var , intvarbool = slices.Grow(, len(`"`)+len()+len(`"`)) = append(, '"')foruint(len()) > uint() {if := []; < utf8.RuneSelf {// Handle single-byte ASCII. ++ifescapeASCII[] == 0 {continue// no escaping possibly needed }// Handle escaping of single-byte ASCII.if !( == '<' || == '>' || == '&') || .Get(jsonflags.EscapeForHTML) { = append(, [:-1]...) = appendEscapedASCII(, ) = } } else {// Handle multi-byte Unicode. , := utf8.DecodeRuneInString(string(truncateMaxUTF8([:]))) += if != utf8.RuneError && != '\u2028' && != '\u2029' {continue// no escaping possibly needed }// Handle escaping of multi-byte Unicode.switch {caseisInvalidUTF8(, ): = true = append(, [:-]...)if .Get(jsonflags.EscapeInvalidUTF8) { = append(, `\ufffd`...) } else { = append(, "\ufffd"...) } = case ( == '\u2028' || == '\u2029') && .Get(jsonflags.EscapeForJS): = append(, [:-]...) = appendEscapedUnicode(, ) = } } } = append(, [:]...) = append(, '"')if && !.Get(jsonflags.AllowInvalidUTF8) {return , ErrInvalidUTF8 }return , nil}func appendEscapedASCII( []byte, byte) []byte {switch {case'"', '\\': = append(, '\\', )case'\b': = append(, "\\b"...)case'\f': = append(, "\\f"...)case'\n': = append(, "\\n"...)case'\r': = append(, "\\r"...)case'\t': = append(, "\\t"...)default: = appendEscapedUTF16(, uint16()) }return}func appendEscapedUnicode( []byte, rune) []byte {if , := utf16.EncodeRune(); != '\ufffd' && != '\ufffd' { = appendEscapedUTF16(, uint16()) = appendEscapedUTF16(, uint16()) } else { = appendEscapedUTF16(, uint16()) }return}func appendEscapedUTF16( []byte, uint16) []byte {const = "0123456789abcdef"returnappend(, '\\', 'u', [(>>12)&0xf], [(>>8)&0xf], [(>>4)&0xf], [(>>0)&0xf])}// ReformatString consumes a JSON string from src and appends it to dst,// reformatting it if necessary according to the specified flags.// It returns the appended output and the number of consumed input bytes.func (, []byte, *jsonflags.Flags) ([]byte, int, error) {// TODO: Should this update ValueFlags as input?varValueFlags , := ConsumeString(&, , !.Get(jsonflags.AllowInvalidUTF8))if != nil {return , , }// If the output requires no special escapes, and the input // is already in canonical form or should be preserved verbatim, // then directly copy the input to the output.if !.Get(jsonflags.AnyEscape) && (.IsCanonical() || .Get(jsonflags.PreserveRawStrings)) { = append(, [:]...) // copy the string verbatimreturn , , nil }// Under [jsonflags.PreserveRawStrings], any pre-escaped sequences // remain escaped, however we still need to respect the // [jsonflags.EscapeForHTML] and [jsonflags.EscapeForJS] options.if .Get(jsonflags.PreserveRawStrings) {var , intfor < {if := []; < utf8.RuneSelf {if ( == '<' || == '>' || == '&') && .Get(jsonflags.EscapeForHTML) { = append(, [:]...) = appendEscapedASCII(, ) = + 1 } ++ } else { , := utf8.DecodeRune(truncateMaxUTF8([:]))if ( == '\u2028' || == '\u2029') && .Get(jsonflags.EscapeForJS) { = append(, [:]...) = appendEscapedUnicode(, ) = + } += } }returnappend(, [:]...), , nil }// The input contains characters that might need escaping, // unnecessary escape sequences, or invalid UTF-8. // Perform a round-trip unquote and quote to properly reformat // these sequences according the current flags. , := AppendUnquote(nil, [:]) , _ = AppendQuote(, , )return , , nil}// AppendFloat appends src to dst as a JSON number per RFC 7159, section 6.// It formats numbers similar to the ES6 number-to-string conversion.// See https://go.dev/issue/14135.//// The output is identical to ECMA-262, 6th edition, section 7.1.12.1 and with// RFC 8785, section 3.2.2.3 for 64-bit floating-point numbers except for -0,// which is formatted as -0 instead of just 0.//// For 32-bit floating-point numbers,// the output is a 32-bit equivalent of the algorithm.// Note that ECMA-262 specifies no algorithm for 32-bit numbers.func ( []byte, float64, int) []byte {if == 32 { = float64(float32()) } := math.Abs() := byte('f')if != 0 {if == 64 && (float64() < 1e-6 || float64() >= 1e21) || == 32 && (float32() < 1e-6 || float32() >= 1e21) { = 'e' } } = strconv.AppendFloat(, , , -1, )if == 'e' {// Clean up e-09 to e-9. := len()if >= 4 && [-4] == 'e' && [-3] == '-' && [-2] == '0' { [-2] = [-1] = [:-1] } }return}// ReformatNumber consumes a JSON string from src and appends it to dst,// canonicalizing it if specified.// It returns the appended output and the number of consumed input bytes.func (, []byte, *jsonflags.Flags) ([]byte, int, error) { , := ConsumeNumber()if != nil {return , , }if !.Get(jsonflags.CanonicalizeNumbers) { = append(, [:]...) // copy the number verbatimreturn , , nil }// Identify the kind of number.varboolfor , := range [:] {if == '.' || == 'e' || == 'E' { = true// has fraction or exponentbreak } }// Check if need to canonicalize this kind of number.switch {casestring([:]) == "-0":break// canonicalize -0 as 0 regardless of kindcase :if !.Get(jsonflags.CanonicalizeRawFloats) { = append(, [:]...) // copy the number verbatimreturn , , nil }default:// As an optimization, we can copy integer numbers below 2⁵³ verbatim // since the canonical form is always identical.const = 16// len(strconv.AppendUint(nil, 1<<53, 10))if !.Get(jsonflags.CanonicalizeRawInts) || < { = append(, [:]...) // copy the number verbatimreturn , , nil } }// Parse and reformat the number (which uses a canonical format). , := strconv.ParseFloat(string([:]), 64)switch {case == 0: = 0// normalize negative zero as just zerocasemath.IsInf(, +1): = +math.MaxFloat64casemath.IsInf(, -1): = -math.MaxFloat64 }returnAppendFloat(, , 64), , nil}
The pages are generated with Goldsv0.7.7-preview. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.