package decoder

import (
	
	
	stderrors 
	
	
	
	
	
	
	

	
	
	
	
)

// The structs and the maps of the semantics of encoding/json/v2. The members of a struct are the fields which
// jsonfields finds, whose names are matched exactly, and by their folded names ( see jsonfields.FoldName ) only if
// their `case` option or V2MatchCaseInsensitiveNames says so. A name of no field is decoded into the embedded
// fallback of the struct, if it has one, or else skipped, or is an error with V2RejectUnknownMembers. An object
// which has a field twice, or a name of no field twice, is an error unless V2AllowDuplicateNames. An object is
// merged into a map, whose entries are decoded into the values they had.

var (
	errNilField         = stderrors.New("cannot set embedded pointer to unexported struct type")
	errInvalidStringTag = stderrors.New("invalid use of `string` tag option")
	errRawNotObject     = stderrors.New("embedded raw value must be a JSON object")
)

// v2StructDecoder is the decoder of a struct of v2.
type v2StructDecoder struct {
	typ  reflect.Type
	zero zeroer
	// initErr is the error of the definition of the struct, which an object of it reports: it has no fields then.
	initErr *jsonfields.Error
	// fields are the fields by their indexes, which are the bits of the set of the fields which an object has.
	// keyDecoder finds the field of a name as v1 finds it, exactly or else by its folded name, which is taken if
	// the name is the name of the field as it is.
	fields     []*structFieldSet
	keyDecoder *structDecoder
	// foldedTo is the field which a name of the folded name of each field matches ( see jsonfields.FoldName ), by the
	// indexes of the fields, in a table for the options ( see foldedOf ): without V2MatchCaseInsensitiveNames, only the
	// fields of the `case:ignore` option match a name so, and with it all but the ones of `case:strict` do; with
	// V2MatchCaseSensitiveDelimiter, only the ones of the name but for the case do, as strings.EqualFold compares
	// names, which v1 finds a name by ( see appendFoldedKey ). It is nil where no field matches the name, and
	// ambiguousField where several do, but the first of them in the breadth-first order of the fields with
	// V2ReportErrorsWithLegacySemantics, as encoding/json chooses it. A name is of the folded name of the field which
	// v1 finds for it, or which foldKeys finds for it without its '_' and '-' ( see foldKey ), but with
	// V2MatchCaseSensitiveDelimiter. foldKeys is a table as v1's of the names of the fields without their '_' and '-',
	// v1's own if no name of a field has them. foldAlways is whether a field matches by its `case:ignore` option,
	// without V2MatchCaseInsensitiveNames.
	foldedTo   [foldedTables][]*structFieldSet
	foldKeys   *structKeys
	foldAlways bool
	fallback   *v2Fallback
}

// The tables of foldedTo of v2StructDecoder, by the options which choose them.
const (
	foldedInsensitive = 1 << iota // V2MatchCaseInsensitiveNames
	foldedDelimiter               // V2MatchCaseSensitiveDelimiter
	foldedTables      = foldedDelimiter << 1
)

// foldedOf returns the table of foldedTo for the options flags: the bit of each option, moved to the bit of its table,
// without a branch.
func ( *v2StructDecoder) ( V2Flags) []*structFieldSet {
	return .foldedTo[(/V2MatchCaseInsensitiveNames&1)*foldedInsensitive|
		(/V2MatchCaseSensitiveDelimiter&1)*foldedDelimiter]
}

// compileStructV2 returns the decoder of the struct type typ. It stays in c.decoders after the compile, as the one
// of compileStruct does, unless a decoder which declines values to it is there ( see compileNextV2 ).
func ( *compiler) ( reflect.Type) (Decoder, error) {
	 := &v2StructDecoder{typ: , zero: newZeroer()}
	if ,  := .decoders[uintptr(runtime.TypePtr())]; ! {
		.decoders[uintptr(runtime.TypePtr())] = 
	}
	 := jsonfields.Of()
	 := .v1Options&V2ReportErrorsWithLegacySemantics != 0
	switch {
	case .Err != nil && !:
		// with ReportErrorsWithLegacySemantics, the fields which jsonfields found are decoded, as encoding/json
		// decodes them
		.initErr = .Err
		return , nil
	case .FormatErr != nil:
		.initErr = .FormatErr
		return , nil
	}
	// the fields whose names may match a name by their folded names, by the folded names
	 := map[string][]*structFieldSet{}
	for  := range .List {
		 := &.List[]
		var  Decoder
		var  error
		if .String && (! || .stringOptionAppliesAsV1(.Type)) {
			,  = .stringTagCompiler().compileV2(.Type, .Name(), .Name)
		} else {
			,  = compile(.Type, .Name(), .Name, )
		}
		if  != nil {
			return nil, 
		}
		,  := fieldPathV2(, , .Index, )
		 := &structFieldSet{dec: .goOnDecoder(), offset: , key: .Name, keyLen: int64(len(.Name)), fieldIdx: }
		.fields = append(.fields, )
		if .Casing&jsonfields.CaseStrict == 0 {
			 := string(jsonfields.FoldName([]byte(.Name)))
			[] = append([], )
			.foldAlways = .foldAlways || .Casing&jsonfields.CaseIgnore != 0
		}
	}
	for  := range .foldedTo {
		.foldedTo[] = make([]*structFieldSet, len(.fields))
	}
	 := onlyField
	if  {
		// the first field in the breadth-first order of the fields, as encoding/json matches a name which several
		// fields match with ReportErrorsWithLegacySemantics
		 = func(,  *structFieldSet) *structFieldSet {
			if  == nil || .List[.fieldIdx].ID < .List[.fieldIdx].ID {
				return 
			}
			return 
		}
	}
	 := false
	for ,  := range .fields {
		for ,  := range [string(jsonfields.FoldName([]byte(.key)))] {
			 := .List[.fieldIdx].Casing&jsonfields.CaseIgnore != 0
			// a name of the field which matches the other field without their '_' and '-' only
			 := !strings.EqualFold(.key, .key)
			// the other field matches the name in the tables of V2MatchCaseInsensitiveNames, and in all if it has
			// case:ignore, but in none of V2MatchCaseSensitiveDelimiter if the names differ in their '_' and '-'
			for  := range .foldedTo {
				if &foldedInsensitive == 0 && ! || &foldedDelimiter != 0 &&  {
					continue
				}
				.foldedTo[][] = (.foldedTo[][], )
			}
		}
		 =  || strings.ContainsAny(.key, "_-")
	}
	 := newStructKeys(.fields)
	.foldKeys = 
	if  {
		// the fields under their names without '_' and '-', of their indexes
		 := make([]*structFieldSet, len(.fields))
		for ,  := range .fields {
			var  [64]byte
			,  := foldKey([:0], []byte(.key))
			 := *
			.key, .keyLen = string(), int64(len())
			[] = &
		}
		.foldKeys = newStructKeys()
	}
	// every name of a field by its bytes as they are, which a name as the input has it is found by ( see
	// plainFieldV2 )
	.makeExact(.fields, true)
	.keyDecoder = &structDecoder{fields: .fields, keys: , stringDecoder: skipStringDecoder}
	if .Fallback != nil {
		,  := .compileFallback(, .Fallback)
		if  != nil {
			return nil, 
		}
		.fallback = 
	}
	return , nil
}

// stringTagCompiler returns the compiler of the values of a field of the `string` option: a number is decoded from
// a JSON string, through the pointers to it, and a value of any other type can't be decoded.
func ( *compiler) () *compiler {
	return &compiler{
		decoders: map[uintptr]Decoder{}, v2: true, stringifyNumbers: true, stringTag: true, v1Options: .v1Options,
		funcs: .funcs,
	}
}

// stringOptionAppliesAsV1 reports whether the `string` option of a field of typ is in effect with
// ReportErrorsWithLegacySemantics, which drops the option of a value which it doesn't apply to, as encoding/json drops
// it: it applies to a value which a function or a method decodes, but a time.Time, to a number, to a time.Duration and
// to a value of a type which has no representation, which fail as they do without it, and with
// StringifyWithLegacySemantics to a bool and a string, through one pointer only. The value which an interface value
// holds, which encoding/json decodes by the option without StringifyWithLegacySemantics, is decoded without it.
func ( *compiler) ( reflect.Type) bool {
	 := 
	// the walk ends where it comes back to a pointer which it passed, in pointers to pointers without an end, as type
	// P *P, which the option doesn't apply to
	var  []reflect.Type
	for .Kind() == reflect.Pointer && len(.funcs.funcsOf()) == 0 {
		if slices.Contains(, ) {
			return false
		}
		 = append(, )
		 = .Elem()
	}
	 := .v1Options&V2StringifyWithLegacySemantics != 0
	switch {
	case  == timeType,  && .Kind() == reflect.Pointer && .Elem().Kind() == reflect.Pointer:
		// a pointer to a pointer, whatever functions the pointers have: the functions are given no option ( see
		// issues/decoder-v2-string-option-of-methods.md ), and the value which one declines is decoded without it,
		// as encoding/json/v2 decodes it
		return false
	case len(.funcs.funcsOf()) > 0 || v2MethodOf(, methodUnmarshalJSONFrom) != noMethod:
		return true
	case isNumberKind(.Kind()) ||  == jsonNumberType:
		return true
	}
	return  && (.Kind() == reflect.Bool || .Kind() == reflect.String)
}

// fieldPathV2 returns the offset of the field of the struct typ at index, by reflect.Type.FieldByIndex, and the
// decoder of its value, which dec decodes: a field in a struct which an embedded pointer points to is decoded
// through the pointer, which is allocated if it is nil and can be set. root is the struct type of the object.
func fieldPathV2(,  reflect.Type,  []int,  Decoder) (uintptr, Decoder) {
	 := .Field([0])
	if len() == 1 {
		return .Offset, 
	}
	if .Type.Kind() == reflect.Pointer {
		,  := (, .Type.Elem(), [1:], )
		return .Offset, &v2EmbeddedPtrDecoder{
			elem: .Type.Elem(), offset: , dec: , settable: .IsExported(), root: ,
		}
	}
	,  := (, .Type, [1:], )
	return .Offset + , 
}

// v2EmbeddedPtrDecoder decodes a field of a struct which an embedded pointer points to, through the pointer: a nil
// pointer is set to a new value, if it can be set, and is an error of the struct of the object, root, else.
type v2EmbeddedPtrDecoder struct {
	elem     reflect.Type
	offset   uintptr
	dec      Decoder
	settable bool
	root     reflect.Type
}

func ( *v2EmbeddedPtrDecoder) ( *RuntimeContext, ,  int64,  unsafe.Pointer) (int64, error) {
	if *(*unsafe.Pointer)() == nil {
		if !.settable {
			 = skipWhiteSpace(.Buf, )
			return 0, &errors.UnmarshalError{GoType: .root, Start: , NoKind: true, Err: errNilField}
		}
		*(*unsafe.Pointer)() = newValue(.elem)
	}
	return .dec.Decode(, , , unsafe.Add(*(*unsafe.Pointer)(), .offset))
}

func ( *v2EmbeddedPtrDecoder) ( *RuntimeContext, ,  int64) ([][]byte, int64, error) {
	return nil, 0, fmt.Errorf("json: v2 decoder does not support decode path")
}

func ( *v2StructDecoder) ( *RuntimeContext, ,  int64,  unsafe.Pointer) (int64, error) {
	 := .Buf
	 = skipWhiteSpace(, )
	switch [] {
	case 'n':
		if  := validateNull(, );  != nil {
			return 0, 
		}
		if .Option.V2&V2MergeWithLegacySemantics == 0 {
			.zero.zero()
		}
		return  + 4, nil
	case '{':
	default:
		return .skipTypeError(, , .typ)
	}
	if .initErr != nil {
		return 0, &errors.UnmarshalError{GoType: .initErr.GoType, Start: , Err: .initErr.Err}
	}
	++
	if  > maxDecodeNestingDepth {
		return 0, errors.ErrExceededMaxDepth([], )
	}
	 = skipWhiteSpace(, +1)
	if [] == '}' {
		return  + 1, nil
	}
	// the loop of the options, which are looked at once for the object: the object of a struct whose names are
	// matched as they are and which has no fallback, without V2RejectUnknownMembers, is decoded by a loop of its own
	// with the text of encoding/json/v2 by default, if the struct has up to seenFields fields, and with the text of v1,
	// as v1 decodes it
	if !.foldAlways && .fallback == nil && .Option.V2&(V2MatchCaseInsensitiveNames|V2RejectUnknownMembers) == 0 {
		switch .Option.V2 & asV1Text {
		case strictText:
			if len(.fields) <= seenFields {
				return .decodeMembersOnce(, , , )
			}
		case asV1Text:
			return .decodeMembersAsV1(, , , )
		}
	}
	// the loop of the other options and structs
	 := .Option.V2&V2AllowDuplicateNames == 0
	 := .foldAlways || .Option.V2&V2MatchCaseInsensitiveNames != 0
	// seen are the fields which the object has, by their bits, after the first seenFields in more, and unknown the
	// names of no field which it has.
	var  uint64
	var  []uint64
	var  nameSet
	for {
		 := 
		if [] != '"' {
			// white space after the comma, which is checked here, as most names follow the comma at once
			if  = skipWhiteSpace(, ); [] != '"' {
				return 0, syntaxErrorAt(, , whereKey)
			}
		}
		var  *structFieldSet
		var  int64
		var  bool
		if  {
			, ,  = .foldedFieldV2(, , )
		} else {
			, ,  = plainFieldV2(.keyDecoder.keys, , )
		}
		// name is the name decoded, which a name of no field is checked by, or nil for a name whose field the lookup
		// decided, which is as the input has it
		var  []byte
		if ! {
			var  error
			if , , ,  = .decodedMember(, , );  != nil {
				return 0, 
			}
		}
		// the name is checked before the colon after it, as encoding/json/v2 reads the name alone
		if  != nil {
			if  {
				if  := .fieldIdx;  < seenFields {
					// the first fields are the bits of seen, in a register
					 := uint64(1) << uint()
					if & != 0 {
						return 0, &errors.UnmarshalError{Start: , Err: errors.ErrDuplicateName}
					}
					 |= 
				} else if fieldSeen(, &, len(.fields)) {
					return 0, &errors.UnmarshalError{Start: , Err: errors.ErrDuplicateName}
				}
			}
		} else if .fallback == nil {
			// a member of no field, whose value is skipped, and the members of no field after it
			, ,  := .skipUnknownMembers(, &, , , , , , )
			if  != nil {
				return 0, 
			}
			if  {
				.end(.v2)
				return , nil
			}
			 = 
			continue
		} else if  := .unknownMember(, &, , , , , );  != nil {
			return 0, 
		}
		if [] == ':' {
			 =  + 1
		} else {
			 = skipWhiteSpace(, )
			if [] != ':' {
				return 0, syntaxErrorAt(, , whereAfterKey)
			}
			++
		}
		var  error
		if  != nil {
			,  = .dec.Decode(, , , unsafe.Add(, .offset))
		} else {
			,  = .fallback.decodeMember(, , , , , )
		}
		if  != nil {
			return 0, 
		}
		 = skipWhiteSpace(, )
		switch [] {
		case '}':
			.end(.v2)
			return  + 1, nil
		case ',':
			++
		default:
			return 0, syntaxErrorAt(, , whereAfterPair)
		}
	}
}

// decodeMembersOnce is the loop of Decode without options, for a struct of up to seenFields fields whose names are
// matched as they are and which has no fallback, from the first name of an object at cursor: a field which the object
// has twice, by the bits of seen, and a name of no field which it has twice, by unknown, are errors, and the values of
// no field are skipped as encoding/json/v2 reads them, for their names and their UTF-8.
func ( *v2StructDecoder) ( *RuntimeContext, ,  int64,  unsafe.Pointer) (int64, error) {
	 := .Buf
	var  uint64
	var  nameSet
	for {
		 := 
		if [] != '"' {
			// white space after the comma, which is checked here, as most names follow the comma at once
			if  = skipWhiteSpace(, ); [] != '"' {
				return 0, syntaxErrorAt(, , whereKey)
			}
		}
		, ,  := plainFieldV2(.keyDecoder.keys, , )
		// name is the name decoded, which a name of no field is checked by, or nil for a name whose field the lookup
		// decided, which is as the input has it
		var  []byte
		if ! {
			var  error
			if , , ,  = .decodedMember(, , );  != nil {
				return 0, 
			}
		}
		// the name is checked before the colon after it, as encoding/json/v2 reads the name alone
		if  != nil {
			 := uint64(1) << uint(.fieldIdx)
			if & != 0 {
				return 0, &errors.UnmarshalError{Start: , Err: errors.ErrDuplicateName}
			}
			 |= 
		} else {
			 := .V2Call()
			var  bool
			if  == nil {
				 = .addListed(, , +1, -1) || .add(, , +1, -1)
			} else {
				 = .addCopy(, , )
			}
			if ! {
				return 0, &errors.UnmarshalError{Start: , Err: errors.ErrDuplicateName}
			}
		}
		if [] == ':' {
			 =  + 1
		} else {
			 = skipWhiteSpace(, )
			if [] != ':' {
				return 0, syntaxErrorAt(, , whereAfterKey)
			}
			++
		}
		var  error
		if  != nil {
			,  = .dec.Decode(, , , unsafe.Add(, .offset))
		} else {
			// the value of no field, as skipValueV2 skips it without options
			switch  = skipWhiteSpace(, ); [] {
			case '{', '[':
				,  = skipNestedV2(, , )
			case '"':
				,  = skipStringV2(, )
			default:
				,  = skipValue(, , )
			}
		}
		if  != nil {
			return 0, 
		}
		 = skipWhiteSpace(, )
		switch [] {
		case '}':
			.end(.v2)
			return  + 1, nil
		case ',':
			++
		default:
			return 0, syntaxErrorAt(, , whereAfterPair)
		}
	}
}

// decodeMembersAsV1 is the loop of Decode with V2AllowDuplicateNames and V2AllowInvalidUTF8, for a struct whose names
// are matched as they are and which has no fallback, from the first name of an object at cursor: the object is
// decoded as v1 decodes it, by the loop of structDecoder.Decode, with the fields found by their names as they are, and
// the values of no field skipped by v1's skip.
func ( *v2StructDecoder) ( *RuntimeContext, ,  int64,  unsafe.Pointer) (int64, error) {
	 := .Buf
	for {
		 := 
		if [] != '"' {
			// white space after the comma, which is checked here, as most names follow the comma at once
			if  = skipWhiteSpace(, ); [] != '"' {
				return 0, syntaxErrorAt(, , whereKey)
			}
		}
		, ,  := plainFieldV2(.keyDecoder.keys, , )
		if ! {
			var  error
			if , , _,  = .decodedMember(, , );  != nil {
				return 0, 
			}
		}
		if [] == ':' {
			 =  + 1
		} else {
			 = skipWhiteSpace(, )
			if [] != ':' {
				return 0, syntaxErrorAt(, , whereAfterKey)
			}
			++
		}
		var  error
		if  != nil {
			,  = .dec.Decode(, , , unsafe.Add(, .offset))
		} else {
			,  = skipValue(, , )
		}
		if  != nil {
			return 0, 
		}
		 = skipWhiteSpace(, )
		switch [] {
		case '}':
			return  + 1, nil
		case ',':
			++
		default:
			return 0, syntaxErrorAt(, , whereAfterPair)
		}
	}
}

// decodedMember returns the field of the name at start in buf, or nil, the position after the name, and the name
// decoded: a name with an escape, a byte which is not ASCII or a control character, a name near the end of the buffer
// ( see plainFieldV2 ), or a name whose field by its folded name is not decided ( see foldedFieldV2 ), which the loops
// of Decode don't find as it is.
func ( *v2StructDecoder) ( *RuntimeContext,  []byte,  int64) (*structFieldSet, int64, []byte, error) {
	, ,  := .keyDecoder.decodeKey(, , false)
	if  != nil {
		return nil, 0, nil, 
	}
	, ,  := .memberOf(, [:], )
	if  != nil {
		if ,  := .(*errors.UnmarshalError);  {
			// an error of the name, at it
			.Start = 
		}
		return nil, 0, nil, 
	}
	return , , , nil
}

// skipUnknownMembers skips the member of no field of a struct without a fallback whose name is at start in buf, before
// end, decoded as name, or nil if Decode found it of no field without decoding it ( see plainFieldV2 and
// foldedFieldV2 ), and the members of no field after it: up to the end of the object, after which it returns the
// position and done, or up to a name which is of a field or which Decode decodes, as a name which is not plain or is
// near the end of the buffer ( see plainFieldV2 ), or whose field by its folded name is not decided ( see
// foldedFieldV2 ), whose position it returns, which Decode reads again. A member of no field is an error with
// V2RejectUnknownMembers. It is a loop of its own, so that the loop of Decode is entered once for the members of no
// field one after another, as most such members are, and the state of that loop is not kept around their calls.
func ( *v2StructDecoder) ( *RuntimeContext,  *nameSet,  bool,  []byte, ,  int64,  []byte,  int64) (int64, bool, error) {
	if .Option.V2&V2RejectUnknownMembers != 0 {
		if .Option.V2&V2ReportErrorsWithLegacySemantics == 0 {
			return 0, false, &errors.UnmarshalError{GoType: .typ, Start: , Err: errors.ErrUnknownName}
		}
		// with ReportErrorsWithLegacySemantics, the error is recorded and the members are decoded on
		.recordUnknownMember(, , )
	}
	 := .Option.V2&V2AllowDuplicateNames == 0
	// the values are skipped as skipValueV2 skips them, by the kind of their first byte: the objects and the arrays by
	// skipNestedV2 unless v2 skips them as v1 does, the strings by skipStringV2 if they must be valid UTF-8, and the
	// others by v1
	 :=  || .Option.V2&V2AllowInvalidUTF8 == 0
	 := .Option.V2&V2AllowInvalidUTF8 == 0
	for {
		if  {
			var  bool
			if  == nil {
				 = .add(.V2Call(), , +1, -1)
			} else {
				 = .addCopy(.V2Call(), , )
			}
			if ! {
				return 0, false, &errors.UnmarshalError{Start: , Err: errors.ErrDuplicateName}
			}
		}
		 := 
		if [] == ':' {
			++
		} else {
			if  = skipWhiteSpace(, ); [] != ':' {
				return 0, false, syntaxErrorAt(, , whereAfterKey)
			}
			++
		}
		var  error
		switch  = skipWhiteSpace(, ); [] {
		case '{', '[':
			if  {
				,  = skipNestedV2(, , )
			} else {
				,  = skipValue(, , )
			}
		case '"':
			if  {
				,  = skipStringV2(, )
			} else {
				,  = skipValue(, , )
			}
		default:
			,  = skipValue(, , )
		}
		if  != nil {
			return 0, false, 
		}
		switch  = skipWhiteSpace(, ); [] {
		case '}':
			return  + 1, true, nil
		case ',':
			++
		default:
			return 0, false, syntaxErrorAt(, , whereAfterPair)
		}
		if  = ; [] != '"' {
			if  = skipWhiteSpace(, ); [] != '"' {
				return 0, false, syntaxErrorAt(, , whereKey)
			}
		}
		var  *structFieldSet
		var  bool
		if  {
			, ,  = .foldedFieldV2(, , )
		} else {
			, ,  = plainFieldV2(.keyDecoder.keys, , )
		}
		if  != nil || ! {
			return , false, nil
		}
		 = nil
	}
}

// unknownMember checks the name of no field at start in buf, before end, decoded as name, or nil if Decode found it of
// no field without decoding it ( see skipUnknownMembers ), of a struct with a fallback: a name which the object had
// before is an error if rejectDuplicateNames. unknown are the names of no field which the object had. It is a function
// of its own, so that the loop of Decode keeps nothing of it.
func ( *v2StructDecoder) ( *RuntimeContext,  *nameSet,  bool,  []byte, ,  int64,  []byte) error {
	if ! {
		return nil
	}
	var  bool
	if  == nil {
		 = .add(.V2Call(), , +1, -1)
	} else {
		 = .addCopy(.V2Call(), , )
	}
	if ! {
		return &errors.UnmarshalError{Start: , Err: errors.ErrDuplicateName}
	}
	return nil
}

func ( *v2StructDecoder) ( *RuntimeContext, ,  int64) ([][]byte, int64, error) {
	return nil, 0, fmt.Errorf("json: v2 decoder does not support decode path")
}

// seenFields is the number of the first fields of a struct which the loops of an object mark met themselves, by the
// bits of a uint64, in a register: the fields after them are marked by fieldSeen.
const seenFields = 64

// fieldSeen reports whether the field of the index, seenFields or more, was met before in an object of n fields, and
// marks it met: its bit is in more, which is made when such a field is met, 64 bits in a word.
func fieldSeen( int,  *[]uint64,  int) bool {
	if * == nil {
		* = make([]uint64, (-seenFields+63)/64)
	}
	 -= seenFields
	,  := &(*)[/64], uint64(1)<<uint(%64)
	 := *& != 0
	* |= 
	return 
}

// plainFieldV2 finds the field of the name at cursor in buf, a quote, if the name has only bytes of ASCII which are
// not an escape or a control character ( a plain name, which most names are ): the field whose name is the name as
// it is. It returns the field or nil, the position after the name, and whether the name is plain. The name is read
// word by word, as decodeKey reads it, up to the capacity of buf, whose nul byte at the end stops a name before it. A
// name which is not plain, or which is near the end of a buffer without room for a word after it, is left to
// decodeKey and memberOf.
func plainFieldV2( *structKeys,  []byte,  int64) (*structFieldSet, int64, bool) {
	 :=  + 1
	if +16 > int64(cap()) {
		return nil, 0, false
	}
	 := load64(, )
	if  := specialKeyBytes();  != 0 {
		// a name of less than 8 bytes, whose word is the bytes before the special byte
		 := int64(bits.TrailingZeros64() / 8)
		if [+] != '"' {
			return nil, 0, false
		}
		 :=  +  + 1
		 &= ( ^ ( - 1)) >> 8
		if !.hasExactLength(int()) {
			return nil, , true
		}
		// the first entry of the name is looked at here, as decodeKey looks at the first entry of a key: most names
		// are found in it
		 := &.exact[indexOf((|bit5)&(1<<(uint()*8&63)-1), 0, .exactShift)]
		if .n == int() && .w0 ==  && .unique != nil {
			return .unique, , true
		}
		if .unique == nil {
			return nil, , true
		}
		return .findExact([:+], , 0), , true
	}
	 :=  + 8
	 := specialKeyBytes(load64(, ))
	for  == 0 {
		 += 8
		if +8 > int64(cap()) {
			return nil, 0, false
		}
		 = specialKeyBytes(load64(, ))
	}
	 += int64(bits.TrailingZeros64() / 8)
	if [] != '"' {
		return nil, 0, false
	}
	if !.hasExactLength(int( - )) {
		return nil,  + 1, true
	}
	return .findExact([:], , load64(, -8)),  + 1, true
}

// foldedPlainFieldV2 is plainFieldV2 for the names which may match a field by their folded names: the field which
// structDecoder.decodeKey finds for a plain name by its folded name, and, for a name of no such field, the number of
// its '_' and '-', which the words of the name are counted for as they are read ( see foldKey ).
func foldedPlainFieldV2( *structKeys,  []byte,  int64) (*structFieldSet, int64, int, bool) {
	 :=  + 1
	if +16 > int64(cap()) {
		return nil, 0, 0, false
	}
	 := load64(, )
	if  := specialKeyBytes();  != 0 {
		 := int64(bits.TrailingZeros64() / 8)
		if [+] != '"' {
			return nil, 0, 0, false
		}
		 :=  +  + 1
		 &= ( ^ ( - 1)) >> 8
		if .hasLength(int()) {
			if  := .findASCII([:+], , 0);  != nil {
				return , , 0, true
			}
		}
		return nil, , dashCount(), true
	}
	 := dashCount()
	 :=  + 8
	 := load64(, )
	 := specialKeyBytes()
	for  == 0 {
		 += dashCount()
		 += 8
		if +8 > int64(cap()) {
			return nil, 0, 0, false
		}
		 = load64(, )
		 = specialKeyBytes()
	}
	 += int64(bits.TrailingZeros64() / 8)
	if [] != '"' {
		return nil, 0, 0, false
	}
	if .hasLength(int( - )) {
		if  := .findASCII([:], , load64(, -8));  != nil {
			return ,  + 1, 0, true
		}
	}
	// the bytes of the last word before the special byte
	return nil,  + 1,  + dashCount(&(-1)), true
}

// dashCount returns the number of the bytes of w which are '_' or '-', which FoldName drops ( see foldKey ).
func dashCount( uint64) int {
	return bits.OnesCount64(byteMask(, '_') | byteMask(, '-'))
}

// foldedFieldV2 finds the field of the name at start in buf, a quote, which may match a field by its folded name, if
// the name is plain ( see foldedPlainFieldV2 ) and its field is decided without memberOf: the field which decodeKey
// finds for it, if its folded name matches that field ( see foldedTo ), or no field, if no field may match it by its
// folded name without its '_' and '-' ( see foldKey ). It returns the field or nil, the position after the name, and
// whether the field is decided so.
func ( *v2StructDecoder) ( *RuntimeContext,  []byte,  int64) (*structFieldSet, int64, bool) {
	, , ,  := foldedPlainFieldV2(.keyDecoder.keys, , )
	if ! {
		return nil, 0, false
	}
	 := .foldedOf(.Option.V2)
	if  != nil {
		return , , [.fieldIdx] == 
	}
	// a name of no field of v1, which the table of the names of the fields without '_' and '-' may find without its
	// own, but not if no field has its length without them, which foldedPlainFieldV2 counts, nor with
	// V2MatchCaseSensitiveDelimiter, where a name matches a field only as v1 finds it
	return nil, , .Option.V2&V2MatchCaseSensitiveDelimiter != 0 ||  == 0 && .foldKeys == .keyDecoder.keys ||
		!.foldKeys.hasLength(int(--2)-)
}

// memberOf returns the field of the name, quoted as the input has it, or nil, and the name decoded if it was: candidate
// is the field which v1 finds, exactly or by its folded name, which is the field if the name is its name as it is. Any
// other name matches the field which its folded name matches ( see foldedTo ), but a name which several fields match so
// is an error, without V2ReportErrorsWithLegacySemantics. A name of a byte which is not ASCII or of an escape must have
// the text which v2 allows.
func ( *v2StructDecoder) ( *RuntimeContext,  []byte,  *structFieldSet) (*structFieldSet, []byte, error) {
	 := [1 : len()-1]
	if  != nil && string() == .key {
		// the name of candidate as it is, which has neither a backslash nor invalid UTF-8 ( see jsonfields.Of ): it
		// has no escape, and nothing to look at
		return , , nil
	}
	 := !hasNotASCIIOrEscape()
	 := .Option.V2&V2MatchCaseInsensitiveNames != 0
	 := .foldedOf(.Option.V2)
	if ! {
		if .Option.V2&V2AllowInvalidUTF8 == 0 && !validV2Text() {
			return nil, nil, errV2Text
		}
		if  = unquotedName();  != nil && string() == .key {
			return , , nil
		}
	}
	var  *structFieldSet
	switch {
	case  != nil:
		// the field of the folded name of candidate, which v1 found by the name folded as FoldName folds it, but for
		// '_' and '-', which no rune folds to: it is the folded name of the name
		 = [.fieldIdx]
	case ( || .foldAlways) && .Option.V2&V2MatchCaseSensitiveDelimiter == 0:
		// the name without its '_' and '-' in the table of the fields without theirs, which folds it as FoldName
		// folds it: v1 found nothing in the same lookup of the name without them in its table. A name of ASCII of
		// a length which no field has without them is of no field, as the lookup finds ( see structKeys.lookup ).
		if  := foldedLength(); ( < len() || .foldKeys != .keyDecoder.keys) && (! || .foldKeys.hasLength()) {
			var  [64]byte
			,  := foldKey([:0], )
			if ,  := .foldKeys.lookup(, stringInfo{firstEscape: -1, nonASCII: });  != nil {
				 = [.fieldIdx]
			}
		}
	}
	if  == ambiguousField {
		// a name which several fields match by its folded name is an error, as in encoding/json/v2, whatever their
		// order, without V2ReportErrorsWithLegacySemantics ( see foldedTo )
		return nil, nil, &errors.UnmarshalError{GoType: .typ, Err: errors.ErrAmbiguousName}
	}
	return , , nil
}

// ambiguousField stands for the fields of a folded name in foldedTo of v2StructDecoder which several fields match.
var ambiguousField = &structFieldSet{}

// onlyField returns the field which a folded name matches when it matched match before, nil if none did, and field
// too ( see foldedTo of v2StructDecoder ).
func onlyField(,  *structFieldSet) *structFieldSet {
	if  == nil {
		return 
	}
	return ambiguousField
}

// foldKey returns name without its '_' and '-', appended to out if it has one of them, and whether it has a byte
// which is not ASCII. FoldName drops them, and no rune folds to them: v1's lookup of the key, which folds names as
// FoldName folds them but for '_' and '-', finds a field of the folded name of the name in a table of the names of
// the fields without them.
func foldKey(,  []byte) ([]byte, bool) {
	,  := 0, false
	for ;  < len() && [] != '_' && [] != '-'; ++ {
		 =  || [] >= utf8.RuneSelf
	}
	if  == len() {
		return , 
	}
	 = append(, [:]...)
	for ,  := range [+1:] {
		if  != '_' &&  != '-' {
			 = append(, )
			 =  ||  >= utf8.RuneSelf
		}
	}
	return , 
}

// foldedLength returns the length of name without its '_' and '-', which foldKey drops.
func foldedLength( []byte) int {
	,  := len(), 0
	for ; +8 <= len();  += 8 {
		 := binary.LittleEndian.Uint64([:])
		 -= bits.OnesCount64(byteMask(, '_') | byteMask(, '-'))
	}
	for ,  := range [:] {
		if  == '_' ||  == '-' {
			--
		}
	}
	return 
}

// hasNotASCIIOrEscape reports whether b has a byte which is not ASCII or a backslash, which it looks for eight bytes
// at a time.
func hasNotASCIIOrEscape( []byte) bool {
	 := 0
	for ; +8 <= len();  += 8 {
		 := binary.LittleEndian.Uint64([:])
		// a backslash is a zero byte of s, whose subtraction sets its top bit
		 :=  ^ ('\\' * lsb)
		if (|(-lsb)&^)&msb != 0 {
			return true
		}
	}
	for ,  := range [:] {
		if  >= 0x80 ||  == '\\' {
			return true
		}
	}
	return false
}

// unquotedName returns the string quoted, as the input has it, decoded.
func unquotedName( []byte) []byte {
	, , ,  := skipStringDecoder.scanString(, 0)
	if  < 0 {
		, _, , _ = skipStringDecoder.scanStringRest(, , --1, )
	}
	return decodeLiteral(, )
}

// skipperOf returns the skipper of the call of ctx of its options, which it takes for the first value: the options
// of a call which a method makes on the context of the call around it may differ. A value is read by a skipper only
// for names twice or invalid UTF-8, which the options don't both allow.
func skipperOf( *RuntimeContext) unsafe.Pointer {
	 := .V2Call()
	 := 0
	switch {
	case .Option.V2&V2AllowDuplicateNames != 0:
		 = 2 // for invalid UTF-8 only
	case .Option.V2&V2AllowInvalidUTF8 != 0:
		 = 1
	}
	if .skippers[] == nil {
		.skippers[] = textcoder.TakeSkipper( == 2,  == 1)
	}
	return .skippers[]
}

// releaseSkippers puts back the skippers which the call took.
func releaseSkippers( *V2Call) {
	for ,  := range .skippers {
		if  != nil {
			textcoder.ReleaseSkipper()
			.skippers[] = nil
		}
	}
}

// v2Fallback is the embedded fallback of a struct, which the members of no field are decoded into: a jsontext.Value,
// which they are appended to, or a map of string keys, whose entries they are.
type v2Fallback struct {
	// steps are the fields on the way to the fallback from the struct, the fallback last: an embedded pointer is
	// allocated if it is nil.
	steps []fallbackStep
	// mapType is the type of a map, whose values value decodes, or nil for a jsontext.Value.
	mapType reflect.Type
	value   Decoder
}

// fallbackStep is a field on the way to an embedded fallback: its offset, and the type which it points to if it is a
// pointer.
type fallbackStep struct {
	offset uintptr
	elem   reflect.Type
}

func ( *compiler) ( reflect.Type,  *jsonfields.Field) (*v2Fallback, error) {
	 := &v2Fallback{}
	 := 
	for ,  := range .Index {
		 := .Field()
		 := fallbackStep{offset: .Offset}
		 = .Type
		if .Kind() == reflect.Pointer {
			.elem,  = .Elem(), .Elem()
		}
		.steps = append(.steps, )
	}
	if  != jsonfields.RawValueType {
		.mapType = 
		,  := compile(.Elem(), "", "", )
		if  != nil {
			return nil, 
		}
		.value = .goOnDecoder()
	}
	return , nil
}

// target returns the address of the fallback of the struct at p.
func ( *v2Fallback) ( unsafe.Pointer) unsafe.Pointer {
	for ,  := range .steps {
		 = unsafe.Add(, .offset)
		if .elem != nil {
			if *(*unsafe.Pointer)() == nil {
				*(*unsafe.Pointer)() = newValue(.elem)
			}
			 = *(*unsafe.Pointer)()
		}
	}
	return 
}

// openRaw returns the jsontext.Value fallback of the struct at p, made ready for one more member to be appended: an
// object without its end and with a comma after its last member. A value which is not an object is an error.
func ( *v2Fallback) ( unsafe.Pointer) (*[]byte, error) {
	 := (*[]byte)(.target())
	if len(*) == 0 {
		* = append(*, '{')
		return , nil
	}
	* = bytes.TrimRight(*, " \t\r\n")
	if len(*) == 0 || (*)[len(*)-1] != '}' {
		return nil, errRawNotObject
	}
	* = bytes.TrimRight((*)[:len(*)-1], " \t\r\n")
	if  := len(*);  == 0 || (*)[-1] != ',' && (*)[-1] != '{' {
		* = append(*, ',')
	}
	return , nil
}

// decodeMember decodes the value at cursor of the member whose name, between start and end of the input, quoted, is
// of no field of the struct at p, into its fallback.
func ( *v2Fallback) ( *RuntimeContext, ,  int64,  unsafe.Pointer, ,  int64) (int64, error) {
	 := .Buf[:]
	 := .target()
	if .mapType == nil {
		// the value which the member is appended to is checked before the value of the member is read
		,  := .openRaw()
		if  != nil {
			// the error of the member, at its name, after whose value the decoding goes on with
			// ReportErrorsWithLegacySemantics
			return .goOnAfter(&errors.UnmarshalError{GoType: jsonfields.RawValueType, Start: , Err: }, , )
		}
		 := skipWhiteSpace(.Buf, )
		,  := .skipValueV2(, )
		if  != nil {
			// a syntax error of the value, which encoding/json/v2 reads whole: the v2 json package reads it whole
			// to find it again ( see readsWhole ).
			return 0, &errors.UnmarshalError{GoType: jsonfields.RawValueType, Start: , Err: }
		}
		* = append(*, ...)
		* = append(*, ':')
		* = append(*, .Buf[:]...)
		* = append(*, '}')
		return , nil
	}
	 := valueAt(ptrTypeOf(.mapType), )
	if .IsNil() {
		.Set(reflect.MakeMap(.mapType))
	}
	 := reflect.ValueOf(string(unquotedName())).Convert(.mapType.Key())
	 := reflect.New(.mapType.Elem())
	if  := .MapIndex(); .IsValid() {
		.Elem().Set()
	}
	,  := .value.Decode(, , , .UnsafePointer())
	.SetMapIndex(, .Elem())
	return , 
}

// compileMapV2 returns the decoder of the map type typ: the names of an object are decoded as the values of the key
// type, but the numbers, which are in the names, as with StringifyNumbers.
func ( *compiler) ( reflect.Type, ,  string) (Decoder, error) {
	if  == interfaceMapType {
		// a function of unmarshaling which takes a string, an interface{} or a type of its values decodes the
		// names or the values: the map is then decoded as any other
		if  := .newV2InterfaceDecoder(emptyInterfaceType); !.fromAny {
			return &v2AnyMapDecoder{iface: }, nil
		}
	}
	 := &v2MapDecoder{typ: , ptrType: ptrTypeOf()}
	if ,  := .decoders[uintptr(runtime.TypePtr())]; ! {
		// a decoder which declines values to it stays there ( see compileNextV2 )
		.decoders[uintptr(runtime.TypePtr())] = 
		defer delete(.decoders, uintptr(runtime.TypePtr()))
	}
	// the keys are compiled apart: a type of them, compiled for the names, is not the one of a value
	 := &compiler{
		decoders: map[uintptr]Decoder{}, v2: true, stringifyNumbers: true, v1Options: .v1Options, mapKeys: true,
		funcs: .funcs,
	}
	,  := .compileV2(.Key(), , )
	if  != nil {
		return nil, 
	}
	,  := compile(.Elem(), , , )
	if  != nil {
		return nil, 
	}
	.keyDecoder, .valueDecoder = , .goOnDecoder()
	return , nil
}

// v2MapDecoder is the decoder of a map of v2. An object is merged into the map: the value of a name which the map
// has as a key is decoded into the value of the key. A name which is the key of an earlier member of the object, by
// its value, is an error unless V2AllowDuplicateNames. null sets the map to nil.
type v2MapDecoder struct {
	typ          reflect.Type
	ptrType      unsafe.Pointer
	keyDecoder   Decoder
	valueDecoder Decoder
}

var emptyStructType = reflect.TypeOf(struct{}{})

// uniqueKeyNames reports whether two names of an object which dec decodes into equal keys of the kind are equal: a
// bool, an integer, and a string, unless its invalid UTF-8 is replaced, which are decoded by their kind. A method
// or a function of unmarshaling may decode two names into one key, and one name into two keys.
func uniqueKeyNames( Decoder,  reflect.Kind,  bool) bool {
	switch .(type) {
	case *v2FuncDecoder, *v2UnmarshalFromDecoder, *v2UnmarshalJSONDecoder, *v2UnmarshalTextDecoder:
		return false
	}
	switch  {
	case reflect.Bool,
		reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
		reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		return true
	case reflect.String:
		return !
	}
	return false
}

func ( *v2MapDecoder) ( *RuntimeContext, ,  int64,  unsafe.Pointer) (int64, error) {
	 := .Buf
	 = skipWhiteSpace(, )
	switch [] {
	case 'n':
		if  := validateNull(, );  != nil {
			return 0, 
		}
		*(*unsafe.Pointer)() = nil
		return  + 4, nil
	case '{':
	default:
		return .skipTypeError(, , .typ)
	}
	++
	if  > maxDecodeNestingDepth {
		return 0, errors.ErrExceededMaxDepth([], )
	}
	 := valueAt(.ptrType, )
	if .IsNil() {
		.Set(reflect.MakeMap(.typ))
	}
	 = skipWhiteSpace(, +1)
	if [] == '}' {
		return  + 1, nil
	}
	 := .Option.V2&V2AllowDuplicateNames == 0
	// the keys of the object, if the map had keys before, which a name of the object can't be told from by the map;
	// and the names of the object as they are written, which a key of another kind than a bool, an integer and a
	// string of valid UTF-8 doesn't tell apart, as a pointer, a float or an interface value, nor a key which a method
	// or a function decodes.
	var  reflect.Value
	if  && .Len() > 0 {
		 = reflect.MakeMap(reflect.MapOf(.typ.Key(), emptyStructType))
	}
	// names are the names of the keys, if two keys may have the same name
	var  nameSet
	 :=  && !uniqueKeyNames(.keyDecoder, .typ.Key().Kind(), .Option.V2&V2AllowInvalidUTF8 != 0)
	,  := reflect.New(.typ.Key()), reflect.New(.typ.Elem())
	for {
		 := 
		if [] != '"' {
			return 0, syntaxErrorAt(, , whereKey)
		}
		.Elem().SetZero()
		,  := .keyDecoder.Decode(, , , .UnsafePointer())
		if  != nil {
			// with ReportErrorsWithLegacySemantics, the member of the key is skipped, and the next one decoded
			if ,  = .goOnAfterKey(, , );  != nil {
				return 0, 
			}
			if  = skipWhiteSpace(, ); [] == '}' {
				.end(.v2)
				return  + 1, nil
			}
			 = skipWhiteSpace(, +1)
			continue
		}
		if  && !.addCopy(.V2Call(), nil, unquotedName([:])) {
			return 0, &errors.UnmarshalError{Start: , Err: errors.ErrDuplicateName}
		}
		 := .Elem()
		if  := .MapIndex(); .IsValid() {
			if  && (!.IsValid() || .MapIndex().IsValid()) {
				return 0, &errors.UnmarshalError{Start: , Err: errors.ErrDuplicateName}
			}
			// the value of the name is decoded into, but replaced with MergeWithLegacySemantics
			if .Option.V2&V2MergeWithLegacySemantics == 0 {
				.Elem().Set()
			} else {
				.Elem().SetZero()
			}
		} else {
			.Elem().SetZero()
		}
		 = skipWhiteSpace(, )
		if [] != ':' {
			return 0, syntaxErrorAt(, , whereAfterKey)
		}
		,  = .valueDecoder.Decode(, +1, , .UnsafePointer())
		.SetMapIndex(, .Elem())
		if .IsValid() {
			.SetMapIndex(, reflect.Zero(emptyStructType))
		}
		if  != nil {
			return 0, 
		}
		 = skipWhiteSpace(, )
		switch [] {
		case '}':
			.end(.v2)
			return  + 1, nil
		case ',':
			 = skipWhiteSpace(, +1)
		default:
			return 0, syntaxErrorAt(, , whereAfterPair)
		}
	}
}

func ( *v2MapDecoder) ( *RuntimeContext, ,  int64) ([][]byte, int64, error) {
	return nil, 0, fmt.Errorf("json: v2 decoder does not support decode path")
}

// v2AnyMapDecoder is the decoder of a map[string]interface{} of v2, which is decoded as the one of an interface{}: a
// nil map as a nil interface{}, by v1, and else merged ( see v2InterfaceDecoder.decodeMerging ).
type v2AnyMapDecoder struct {
	iface *v2InterfaceDecoder
}

func ( *v2AnyMapDecoder) ( *RuntimeContext, ,  int64,  unsafe.Pointer) (int64, error) {
	 := .Buf
	 = skipWhiteSpace(, )
	switch [] {
	case 'n':
		if  := validateNull(, );  != nil {
			return 0, 
		}
		*(*unsafe.Pointer)() = nil
		return  + 4, nil
	case '{':
	default:
		return .skipTypeError(, , interfaceMapType)
	}
	 := *(*map[string]any)()
	var  any
	var  int64
	var  error
	if  == nil {
		,  = .iface.Decode(, , , unsafe.Pointer(&))
	} else {
		 = 
		,  = .iface.decodeMerging(, , , unsafe.Pointer(&))
	}
	if ,  := .(map[string]any);  {
		*(*map[string]any)() = 
	}
	return , 
}

func ( *v2AnyMapDecoder) ( *RuntimeContext, ,  int64) ([][]byte, int64, error) {
	return nil, 0, fmt.Errorf("json: v2 decoder does not support decode path")
}