// 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.jsonv2

package jsonwire

import (
	
	
	
	
	

	
)

// 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 characters
	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // escape control characters
	0, 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 {
	var  int
	for uint(len()) > uint() {
		if  := [];  < utf8.RuneSelf {
			if escapeASCII[] > 0 {
				return true
			}
			++
		} else {
			,  := utf8.DecodeRuneInString(string(truncateMaxUTF8([:])))
			if  == utf8.RuneError ||  == '\u2028' ||  == '\u2029' {
				return true
			}
			 += 
		}
	}
	return false
}

// 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 ,  int
	var  bool
	 = slices.Grow(, len(`"`)+len()+len(`"`))
	 = append(, '"')
	for uint(len()) > uint() {
		if  := [];  < utf8.RuneSelf {
			// Handle single-byte ASCII.
			++
			if escapeASCII[] == 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 {
			case isInvalidUTF8(, ):
				 = 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"
	return append(, '\\', '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?
	var  ValueFlags
	,  := 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 verbatim
		return , , 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 ,  int
		for  <  {
			if  := [];  < utf8.RuneSelf {
				if ( == '<' ||  == '>' ||  == '&') && .Get(jsonflags.EscapeForHTML) {
					 = append(, [:]...)
					 = appendEscapedASCII(, )
					 =  + 1
				}
				++
			} else {
				,  := utf8.DecodeRune(truncateMaxUTF8([:]))
				if ( == '\u2028' ||  == '\u2029') && .Get(jsonflags.EscapeForJS) {
					 = append(, [:]...)
					 = appendEscapedUnicode(, )
					 =  + 
				}
				 += 
			}
		}
		return append(, [:]...), , 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 verbatim
		return , , nil
	}

	// Identify the kind of number.
	var  bool
	for ,  := range [:] {
		if  == '.' ||  == 'e' ||  == 'E' {
			 = true // has fraction or exponent
			break
		}
	}

	// Check if need to canonicalize this kind of number.
	switch {
	case string([:]) == "-0":
		break // canonicalize -0 as 0 regardless of kind
	case :
		if !.Get(jsonflags.CanonicalizeRawFloats) {
			 = append(, [:]...) // copy the number verbatim
			return , , 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 verbatim
			return , , nil
		}
	}

	// Parse and reformat the number (which uses a canonical format).
	,  := strconv.ParseFloat(string([:]), 64)
	switch {
	case  == 0:
		 = 0 // normalize negative zero as just zero
	case math.IsInf(, +1):
		 = +math.MaxFloat64
	case math.IsInf(, -1):
		 = -math.MaxFloat64
	}
	return AppendFloat(, , 64), , nil
}