package jsontext

import (
	
	
	
	
	
	
	
	

	
)

// Value is a raw JSON value, one of:
//   - a JSON literal (i.e., null, true, or false)
//   - a JSON string (e.g., "hello, world!")
//   - a JSON number (e.g., 123.456)
//   - a whole JSON object (e.g., {"fizz":"buzz"} )
//   - a whole JSON array (e.g., [1,2,3] )
//
// A Value can hold a whole object or array, which a Token can't. A Value may have leading and trailing white
// space.
type Value []byte //nolint:recvcheck // the methods of encoding/json/jsontext.Value

// Clone returns a copy of v.
func ( Value) () Value {
	return bytes.Clone()
}

// String returns the text of v, or null for a nil v.
func ( Value) () string {
	if  == nil {
		return "null"
	}
	return string()
}

// Kind returns the kind of the first token of v. A valid value never starts with KindEndObject or
// KindEndArray.
func ( Value) () Kind {
	// a value without leading white space, as most are, is looked at without a call
	if len() > 0 && [0] > ' ' {
		return kindOf([0])
	}
	if  := skipSpace(, 0);  < len() {
		return kindOf([])
	}
	return KindInvalid
}

// MarshalJSON returns v as its JSON encoding, without validating it. It returns null for a nil v.
func ( Value) () ([]byte, error) {
	if  == nil {
		return []byte("null"), nil
	}
	return , nil
}

// UnmarshalJSON sets v to a copy of b, without validating it.
func ( *Value) ( []byte) error {
	if  == nil {
		return errors.New("jsontext.Value: UnmarshalJSON on nil pointer")
	}
	* = append((*)[:0], ...)
	return nil
}

// IsValid reports whether v is valid JSON under the options.
//
// Without options, it validates v as RFC 7493 specifies: v is valid UTF-8, the escape sequences of the strings
// are of valid Unicode code points, and the names of each object are unique. It doesn't check whether the
// numbers fit in any numeric type (e.g., float64, int64 or uint64).
//
// The options which matter are AllowDuplicateNames and AllowInvalidUTF8; the others are ignored.
func ( Value) ( ...Options) bool {
	 := getEncoder()
	defer putEncoder()
	.vs.write, .vs.spaced = false, false
	return .writeValue() == nil
}

// Format formats v in place.
//
// Without options, it validates v as RFC 7493 specifies, and writes it in its minimal form: without white
// space, and the strings in their shortest encoding.
//
// The options which matter are AllowDuplicateNames, AllowInvalidUTF8, EscapeForHTML, EscapeForJS,
// PreserveRawStrings, CanonicalizeRawInts, CanonicalizeRawFloats, ReorderRawObjects, SpaceAfterColon,
// SpaceAfterComma, Multiline, WithIndent and WithIndentPrefix; the others are ignored.
//
// It succeeds if v is valid under the same options. If v is formatted already, it is not changed.
func ( *Value) ( ...Options) error {
	return .format(nil, )
}

// Compact removes the white space of v.
//
// It doesn't change the representation of the strings and numbers. So that it formats as many values as it
// can, it takes values of duplicate names and invalid UTF-8.
//
// It is Value.Format with the options AllowDuplicateNames(true), AllowInvalidUTF8(true),
// PreserveRawStrings(true), Multiline(false), SpaceAfterColon(false) and SpaceAfterComma(false), and an empty
// indentation, followed by the options given.
func ( *Value) ( ...Options) error {
	return .format(compactOptions, )
}

var compactOptions = []Options{
	AllowDuplicateNames(true), AllowInvalidUTF8(true), PreserveRawStrings(true), noWhiteSpace,
}

// noWhiteSpace sets the options of white space to none, so that an option given after it changes only itself.
var noWhiteSpace = &config{Set: multiline | spaceAfterColon | spaceAfterComma | indentSet}

// Indent formats the white space of v so that each element of an object or array starts a line which is
// indented by its depth.
//
// It doesn't change the representation of the strings and numbers. So that it formats as many values as it
// can, it takes values of duplicate names and invalid UTF-8.
//
// It is Value.Format with the options AllowDuplicateNames(true), AllowInvalidUTF8(true),
// PreserveRawStrings(true), Multiline(true), SpaceAfterColon(true) and WithIndent("\t"), followed by the options
// given.
func ( *Value) ( ...Options) error {
	return .format(indentOptions, )
}

var indentOptions = []Options{
	AllowDuplicateNames(true), AllowInvalidUTF8(true), PreserveRawStrings(true),
	&config{Set: multiline | spaceAfterColon | indentSet, Value: multiline | spaceAfterColon, Indent: "\t"},
}

// Canonicalize formats v in the canonical form of the JSON Canonicalization Scheme (JCS) of RFC 8785: a value
// of the same meaning, which Canonicalize doesn't change.
//
// The strings are in their minimal form, the numbers are formatted as double precision numbers, the members of
// the objects are sorted by their names, and the white space is removed.
//
// It is Value.Format with the options CanonicalizeRawInts(true), CanonicalizeRawFloats(true),
// ReorderRawObjects(true), Multiline(false), SpaceAfterColon(false) and SpaceAfterComma(false), and an empty
// indentation, followed by the options given.
//
// JCS takes all JSON numbers as IEEE 754 double precision numbers: a number which needs more precision loses
// it. For example, integers beyond ±2⁵³ lose their precision. To keep the representation of the integers, set
// CanonicalizeRawInts to false:
//
//	v.Canonicalize(jsontext.CanonicalizeRawInts(false))
func ( *Value) ( ...Options) error {
	return .format(canonicalOptions, )
}

var canonicalOptions = []Options{CanonicalizeRawInts(true), CanonicalizeRawFloats(true), ReorderRawObjects(true), noWhiteSpace}

func ( *Value) (,  []Options) error {
	 := getEncoder(, ...)
	.buf = slices.Grow(.buf, len(*))
	defer putEncoder()
	.vs.keep = true
	if  := .writeValue(*);  != nil {
		return 
	}
	if .vs.kept {
		return nil // v is formatted already
	}
	if !bytes.Equal(*, .buf) {
		* = append((*)[:0], .buf...)
	}
	return nil
}

// AppendFormat appends the JSON value src to dst, formatted as the options say. See Value.Format for how it
// formats values.
//
// dst and src may overlap. At an error, all of src is appended to dst.
func [ ~[]byte | ~string]( []byte,  ,  ...Options) ([]byte, error) {
	 := getEncoder()
	defer putEncoder()
	.buf = slices.Grow(.buf, len())
	.vs.keep = true
	// the value is only read, which a string may be without a copy.
	if  := .writeValue(readOnlyBytes());  != nil {
		return append(, ...), 
	}
	if .vs.kept {
		return append(, ...), nil // src is formatted already
	}
	return append(, .buf...), nil
}

// encoders are the encoders of the functions and methods which format a single value.
var encoders sync.Pool

// getEncoder returns an encoder of the options first and opts, which writes to its buffer only, without a line
// feed after the value.
func getEncoder( []Options,  ...Options) *encoder {
	,  := encoders.Get().(*encoder)
	if  == nil {
		 = new(encoder)
		.vs.open = new([64]openObject)
	}
	.cfg = config{}
	.cfg.Apply()
	.cfg.Apply()
	.cfg.Set |= omitTopLevelNewline
	.cfg.Value |= omitTopLevelNewline
	.init(nil)
	return 
}

func putEncoder( *encoder) {
	// a large buffer is kept only if it was used well, so that one large value doesn't keep it for small ones.
	if cap(.buf) > 64<<10 && len(.buf) < cap(.buf)/4 {
		.buf = nil
	}
	// neither are the arrays of the names and of the reordered members of a large value.
	const  = 64 << 10
	if cap(.vs.ro.buf) >  || cap(.vs.ro.names) >  || cap(.vs.ro.members) > /32 {
		.vs.ro = reorderer{}
	}
	if cap(.st.names.buf) >  || cap(.st.names.ends) > /8 {
		.st.names = names{}
	}
	.vs.out = nil
	encoders.Put()
}

// AppendQuote appends src to dst as a JSON string, in its minimal form of RFC 8785, section 3.2.2.2, and returns
// the extended buffer. Invalid UTF-8 is appended as the Unicode replacement character, and reported by an error
// at the end. dst must not overlap src.
func [ ~[]byte | ~string]( []byte,  ) ([]byte, error) {
	// the room of the quoted src is made first, as encoding/json/jsontext makes it: a dst which has less isn't
	// written to.
	 = slices.Grow(, len()+2)
	 := readOnlyBytes()
	if overlaps(, [len():]) {
		// src in the room of dst, which the caller must not give: the output would be written over src, which
		// is read from a copy.
		 = bytes.Clone()
	}
	,  := appendQuoted(, unsafe.String(unsafe.SliceData(), len()), 0)
	if ! {
		return , &SyntacticError{Err: errInvalidUTF8}
	}
	return , nil
}

// AppendUnquote appends the value of the JSON string src to dst and returns the extended buffer. src must be a
// JSON string, without white space around it. Invalid UTF-8 is appended as the Unicode replacement character,
// and reported by an error at the end. Bytes after the string are an error. dst must not overlap src.
func [ ~[]byte | ~string]( []byte,  ) ([]byte, error) {
	 = slices.Grow(, len()) // not nil, as encoding/json/jsontext returns it, when src isn't empty
	 := []byte()
	if overlaps(, [len():]) {
		// src in the room of dst, which the caller must not give: the output would be written over src, which
		// is read from a copy, so that it doesn't panic.
		 = bytes.Clone()
	}
	if len() == 0 || [0] != '"' {
		var  error = &SyntacticError{Err: invalidChar(, placeStartOfString)}
		if len() == 0 {
			 = &SyntacticError{Err: io.ErrUnexpectedEOF}
		}
		return , 
	}
	, ,  := scanString(, 0)
	if  != nil {
		// the characters before the error
		return appendUnquotedPrefix(, [:], ), &SyntacticError{Err: }
	}
	 = appendUnquoted(, [:], )
	if  < len() {
		return , &SyntacticError{Err: invalidChar([:], placeAfterString)}
	}
	if &strInvalidUTF8 != 0 {
		// the last invalid UTF-8 or escaped surrogate which is not in a pair, which were mangled
		var  error
		for  := 1; ; {
			, _,  = scanStringFrom(, , 0, strValid)
			if  == nil {
				break
			}
			 = 
			if [] == '\\' {
				 += len(`\uXXXX`)
			} else {
				++
			}
		}
		return , &SyntacticError{Err: }
	}
	return , nil
}

// appendUnquotedPrefix appends the value of the start of a JSON string, which has no quote at its end, and which
// scanString took with the flags f up to an error: its escape sequences are complete.
func appendUnquotedPrefix(,  []byte,  strFlags) []byte {
	return appendUnquoted(, append([:len():len()], '"'), )
}

// AppendFloat appends src to dst as a JSON number of RFC 8259, section 6, with bits of precision.
//
// Except for -0, which it writes as -0, it writes a number as ECMA-262, 10th edition, section 7.1.12.1 does, and,
// with 64 bits, as RFC 8785, section 3.2.2.3 does. NaN, +Inf and -Inf are written as NaN, +Inf and -Inf.
//
// Most JSON libraries and standards take JSON numbers as 64-bit floating-point numbers: use 64 bits of
// precision unless the reader of the number knows that it has 32 bits of precision.
func ( []byte,  float64,  int) []byte {
	if  != 32 &&  != 64 {
		panic("illegal AppendFloat bit size")
	}
	if  == 32 {
		 = float64(float32())
	}
	if math.IsNaN() || math.IsInf(, 0) {
		return strconv.AppendFloat(, , 'g', -1, )
	}
	return floatfmt.AppendFloat(, , )
}