package decoder

import (
	
	
	
	

	
	
)

type RuntimeContext struct {
	Buf    []byte
	Option *Option
	// slot is where a value of interface{} is decoded before it is put into a map or a slice.
	// The decoders of the values nested in it use it too: each of them takes the value out of it
	// before the next value is decoded, and puts its own value into it only at its end.
	slot any
	// anyStack holds the elements of the arrays being decoded into []interface{}: an array pushes
	// its elements above the ones of the arrays it is nested in, and pops them at its end. The objects
	// being decoded into new maps of map[string]interface{} push their entries to entryStack, a key and its
	// value at once, so that a map is made of the size of its object ( see decodeNewStringAnyMap ).
	anyStack   []any
	entryStack []anyEntry
	// input is the buffer which the input of Unmarshal is copied to, followed by a nul byte. It is reused by
	// the calls: nothing decoded refers to it, because the decoded strings are copied out of it ( makeString ).
	input []byte
	// origin is the input of the call at the offsets of Buf: the input of Unmarshal, which Buf is the reused copy
	// of, or Buf itself, as the buffer of a stream. The decoded strings refer to it under NoCopyStringOption.
	origin []byte
	// unescaped is where an escaped string is decoded to before it is copied, which is kept from a call to the next
	// up to maxUnescapeScratchSize ( see unescapeString ).
	unescaped []byte
	// value is a zero value of the type valueType in the heap, which UnmarshalOf decodes into
	// before it copies the result to the value of the caller.
	valueType unsafe.Pointer
	value     unsafe.Pointer
	// recentDecoders are the decoders of the types decoded last, in the sets indexed by the address of the type,
	// and the decoders of v2 by the address marked by its lowest bits ( see DecoderOfV2 ). Only the contexts of the
	// pool and of the streams of v2, which pools keep too, have them: a Decoder has a context of its own, which it
	// would allocate with them for every stream.
	recentDecoders *[recentDecoderSets]recentDecoderSet
	// recentV1Options are the options of encoding/json which change the decoders ( see v1DecoderOptions ) that the
	// decoders of v2 of recentDecoders were compiled for: their keys have no room for them, so the recent decoders are
	// emptied when a decoding has others ( see SetV2Flags ).
	recentV1Options V2Flags
	// v2 is the state of the calls of the v2 json package which use the context, which is kept with it once a call
	// made it ( see V2Call ).
	v2 *V2Call
	// typeError is the first type error of the decoding, which is returned at its end ( see TypeError ). It is nil
	// in a context of the pool: TypeError clears it, and DiscardTypeError when the decoding fails.
	typeError *pendingTypeError
	// path is the copy of the Path which the decoding selects by ( see SetPath ). It is in the context, which is
	// kept, so that the copy costs no allocation.
	path Path
}

// SetPath makes the decoding select the values of p. It selects by a copy of p, as it moves the node of the path it
// is at: p stays as it is for the next call, after one which fails too, and for the calls which other goroutines make
// at the same time.
func ( *RuntimeContext) ( *Path) {
	.path = *
	.Option.Path = &.path
}

const (
	// recentDecoderSets is the number of the sets of the recent decoders, of recentDecoderWays entries each,
	// as the recent opcodes of the encoder: the set of a type is the top bits of the product of its address
	// with an odd constant, and a set holds the two types hashed to it which were decoded last, so that the
	// type passed to Unmarshal and a type held by its values of interface{} never evict each other.
	recentDecoderSets      = 16
	recentDecoderHashShift = 64 - 4
	recentDecoderWays      = 2
)

type recentDecoder struct {
	typeptr uintptr
	dec     Decoder
}

// recentDecoderSet is the entries of a set, the one decoded last first.
type recentDecoderSet [recentDecoderWays]recentDecoder

// DecoderOf returns the decoder of the type, compiling it if the type is new.
//
// A runtime context remembers the decoders of the types it decoded last: the same types are decoded again
// and again in most of the programs, and this is cheaper than a lookup of the table shared by every goroutine.
// The first entry of the set is looked at here; the rest in lookupDecoder.
func ( *RuntimeContext) ( unsafe.Pointer) (Decoder, error) {
	if .recentDecoders == nil {
		return CompileToGetDecoder()
	}
	 := &.recentDecoders[(uint64(uintptr())*runtime.TypeHashMultiplier)>>recentDecoderHashShift]
	if [0].typeptr == uintptr() {
		return [0].dec, nil
	}
	return lookupDecoder(, )
}

// lookupDecoder returns the decoder of the type from the second entry of its set, or from the shared table,
// compiling it if the type is new. A decoder found in the shared table takes the first entry of the set,
// and the one decoded before it is kept in the second.
func lookupDecoder( *recentDecoderSet,  unsafe.Pointer) (Decoder, error) {
	if [1].typeptr == uintptr() {
		return [1].dec, nil
	}
	,  := CompileToGetDecoder()
	if  != nil {
		return nil, 
	}
	.keep(uintptr(), )
	return , nil
}

// keep puts dec, the decoder of the key, in the first entry of the set, and the decoder of the first entry in the
// second.
func ( *recentDecoderSet) ( uintptr,  Decoder) {
	[1] = [0]
	[0] = recentDecoder{typeptr: , dec: }
}

// maxUnescapeScratchSize is the length of the longest escaped string which is decoded into the scratch bytes of a
// context: a longer one is decoded into bytes of its own, which the context doesn't keep.
const maxUnescapeScratchSize = 64 << 10

// inputPadding is the number of the bytes the buffer of the input has after its nul byte, which the decoders
// may read: the words of an object key are read from any byte of the buffer ( see structDecoder.Decode ).
const inputPadding = 16

// SetInput copies data to the buffer of the context, followed by a nul byte which ends every scan,
// and makes it the buffer to decode.
func ( *RuntimeContext) ( []byte) []byte {
	 := len() + 1
	if cap(.input) < +inputPadding {
		// at least a cache line, which the buffer of another context doesn't share: it is written for every call.
		.input = make([]byte, , max(+inputPadding, cacheLineSize))
	}
	 := .input[:]
	copy(, )
	[len()] = nul
	.Buf = 
	.origin = 
	return 
}

// SetBuf makes buf, an input followed by a nul byte which the caller keeps, the input of the decoding of ctx, whose
// strings are copied out of it, as they are out of an input of SetInput. A nil buf drops it. It is a function, not
// a method: a method of the context moves the data of the binary ( its method table ), which slows its decoding.
func ( *RuntimeContext,  []byte) {
	.Buf, .origin = , 
}

// makeString returns the string of lit, which the string decoder returned from Buf: lit is either a part of Buf,
// which has the bytes of the input ( Buf is never written ), or a new slice of its own ( an escape was decoded, or
// an invalid UTF-8 sequence was replaced ).
//
// The string is a copy in memory of its own, as encoding/json makes it, so that a decoded value keeps alive no
// memory but its own: Buf is reused by the next call or the next read, and the input is the caller's. Under
// NoCopyStringOption, it refers to the input instead ( see referString ).
func ( *RuntimeContext) ( []byte) string {
	if (.Option.Flags & NoCopyStringOption) != 0 {
		return .referString()
	}
	return string()
}

// isPartOf reports whether b is a part of buf.
func isPartOf(,  []byte) bool {
	 := uintptr(unsafe.Pointer(unsafe.SliceData()))
	 := uintptr(unsafe.Pointer(unsafe.SliceData()))
	return  <=  &&  < +uintptr(len())
}

// referString returns a string which refers to the input, where lit is a part of Buf, without a copy.
func ( *RuntimeContext) ( []byte) string {
	if len() == 0 {
		// no reference to the input, which an empty string would keep alive
		return ""
	}
	if !isPartOf(, .Buf) {
		// a slice of its own
		return unsafe.String(unsafe.SliceData(), len())
	}
	 := uintptr(unsafe.Pointer(unsafe.SliceData())) - uintptr(unsafe.Pointer(unsafe.SliceData(.Buf)))
	return unsafe.String(&.origin[], len())
}

// popAny removes the elements of anyStack from base, clearing them so that the stack keeps nothing alive.
func ( *RuntimeContext) ( int) {
	clear(.anyStack[:])
	.anyStack = .anyStack[:]
}

// anyEntry is an entry of an object being decoded into a map[string]interface{}.
type anyEntry struct {
	key   string
	value any
}

// popEntries removes the entries of entryStack from base, clearing them so that the stack keeps nothing alive.
func ( *RuntimeContext) ( int) {
	clear(.entryStack[:])
	.entryStack = .entryStack[:]
}

// cacheLineSize is the size of the cache lines the contexts are kept apart by: 128 bytes, which is the line of
// the Apple M processors and two lines of amd64, whose adjacent lines are fetched together.
const cacheLineSize = 128

// pooledContext is a context of the pool with its option, in one allocation which fills its cache lines: the
// contexts of the goroutines which decode at the same time are written for every call, so a context which
// shared a cache line with another made each goroutine wait for the other.
type pooledContext struct {
	ctx RuntimeContext
	opt Option
	_   [cacheLineSize - (unsafe.Sizeof(RuntimeContext{})+unsafe.Sizeof(Option{}))%cacheLineSize]byte
}

var (
	runtimeContextPool = sync.Pool{
		New: func() any {
			 := &pooledContext{}
			.ctx.Option = &.opt
			.ctx.recentDecoders = &[recentDecoderSets]recentDecoderSet{}
			return &.ctx
		},
	}
)

func () *RuntimeContext {
	return runtimeContextPool.Get().(*RuntimeContext)
}

func ( *RuntimeContext) {
	// Nothing of the call is kept: the input of the caller may be referred to by the decoded strings.
	.Buf = nil
	.origin = nil
	.slot = nil
	.popAny(0)
	.popEntries(0)
	// nor what the caller gave to the call: the context of UnmarshalContext and the path of Path
	.Option.Context = nil
	if .Option.Path != nil {
		.Option.Path, .path = nil, Path{}
	}
	if  := .v2;  != nil {
		if len(.names.entries) != 0 {
			.names.truncate(0, 0)
		}
		if .skippers != [3]unsafe.Pointer{} {
			releaseSkippers()
		}
	}
	runtimeContextPool.Put()
}

var (
	isWhiteSpace = [256]bool{}
)

func init() {
	isWhiteSpace[' '] = true
	isWhiteSpace['\n'] = true
	isWhiteSpace['\t'] = true
	isWhiteSpace['\r'] = true
}

func char( unsafe.Pointer,  int64) byte {
	return *(*byte)(unsafe.Add(, ))
}

func skipWhiteSpace( []byte,  int64) int64 {
	for isWhiteSpace[[]] {
		++
	}
	return 
}

// skipStringDecoder scans the strings which skipValue skips.
var skipStringDecoder = newStringDecoder("", "")

// skipString returns the position after the string at cursor. A string without an escape is skipped word by
// word up to its quote, where the buffer has room for the words ( the nul byte at its end stops them ), and, where the CPU has a SIMD scan, for its
// first 64 bytes, after which the rest of a long string is scanned by SIMD ( see scanStringRest ). Any other
// string is scanned as a string is decoded, and validated so. It is a function of its own, so that the code of
// skipValue for the other values is the same whatever a string takes.
func skipString( []byte,  int64) (int64, error) {
	 :=  + 1
	 := int64(len())
	if hasStringSIMD {
		 = min(, +64)
	}
	 := 
	for ; +8 <= ;  += 8 {
		if  := keyEndBytes(load64(, ));  != 0 {
			 += int64(bits.TrailingZeros64() / 8)
			if [] == '"' {
				return  + 1, nil
			}
			// an escape or a byte which is not valid in a string
			return skipStringByScan(, )
		}
	}
	if +8 > int64(len()) {
		// the end of the buffer, whose last bytes are scanned as a string
		return skipStringByScan(, )
	}
	, , ,  := skipStringDecoder.scanStringRest(, [:], , stringInfo{firstEscape: -1})
	if  != nil {
		return 0, 
	}
	return , nil
}

// skipStringByScan is skipString for any string, which it scans as a string is decoded.
func skipStringByScan( []byte,  int64) (int64, error) {
	, , ,  := skipStringDecoder.scanString(, )
	if  < 0 {
		_, , _,  = skipStringDecoder.scanStringRest(, , --1, )
	}
	if  != nil {
		return 0, 
	}
	return , nil
}

func skipValue( []byte, ,  int64) (int64, error) {
	for {
		switch [] {
		case ' ', '\t', '\n', '\r':
			++
			continue
		case '{', '[':
			// the grammar of the object or the array, by skipFast without the call of skipGrammarFast
			, , , ,  := skipFast(, , 0, 0, resumeValue, skipMaxLevel())
			if  == skipDone {
				return , nil
			}
			return skipGrammarEvent(, , , , , , )
		case '"':
			,  := skipString(, )
			if  != nil {
				return 0, stringError(, , )
			}
			return , nil
		case '1', '2', '3', '4', '5', '6', '7', '8', '9':
			// an integer, which most numbers are, without a call
			 := 
			++
			for []-'0' <= 9 {
				++
			}
			if  := [];  == '.' ||  == 'e' ||  == 'E' {
				return skipNumberRest(, , )
			}
			return , nil
		case '-', '0':
			return skipNumber(, )
		case 't':
			if [+1] != 'r' || [+2] != 'u' || [+3] != 'e' {
				return 0, literalSyntaxError(, , "true")
			}
			return  + 4, nil
		case 'f':
			if [+1] != 'a' || [+2] != 'l' || [+3] != 's' || [+4] != 'e' {
				return 0, literalSyntaxError(, , "false")
			}
			return  + 5, nil
		case 'n':
			if [+1] != 'u' || [+2] != 'l' || [+3] != 'l' {
				return 0, literalSyntaxError(, , "null")
			}
			return  + 4, nil
		default:
			return 0, syntaxErrorAt(, , whereValue)
		}
	}
}

func validateTrue( []byte,  int64) error {
	if +3 >= int64(len()) {
		return errors.ErrUnexpectedEndOfJSON("true", )
	}
	if [+1] != 'r' {
		return errors.ErrInvalidCharacter([+1], "true", +1)
	}
	if [+2] != 'u' {
		return errors.ErrInvalidCharacter([+2], "true", +2)
	}
	if [+3] != 'e' {
		return errors.ErrInvalidCharacter([+3], "true", +3)
	}
	return nil
}

func validateFalse( []byte,  int64) error {
	if +4 >= int64(len()) {
		return errors.ErrUnexpectedEndOfJSON("false", )
	}
	if [+1] != 'a' {
		return errors.ErrInvalidCharacter([+1], "false", +1)
	}
	if [+2] != 'l' {
		return errors.ErrInvalidCharacter([+2], "false", +2)
	}
	if [+3] != 's' {
		return errors.ErrInvalidCharacter([+3], "false", +3)
	}
	if [+4] != 'e' {
		return errors.ErrInvalidCharacter([+4], "false", +4)
	}
	return nil
}

func validateNull( []byte,  int64) error {
	if +3 >= int64(len()) {
		return errors.ErrUnexpectedEndOfJSON("null", )
	}
	if [+1] != 'u' {
		return errors.ErrInvalidCharacter([+1], "null", +1)
	}
	if [+2] != 'l' {
		return errors.ErrInvalidCharacter([+2], "null", +2)
	}
	if [+3] != 'l' {
		return errors.ErrInvalidCharacter([+3], "null", +3)
	}
	return nil
}

// valuePools are the zero values of every type which UnmarshalOf decoded, besides the one a context keeps.
var valuePools runtime.TypeCache[sync.Pool]

// TakeValue returns the address of a zero value of typ in the heap, which the context keeps for the next call
// with the same type. typ is given as its type descriptor too, which is how it is looked up.
func ( *RuntimeContext) ( reflect.Type,  unsafe.Pointer) unsafe.Pointer {
	if .valueType ==  {
		return .value
	}
	if .valueType != nil {
		valuePool(.valueType).Put(.value)
	}
	.valueType = 
	if  := valuePool().Get();  != nil {
		.value = .(unsafe.Pointer)
	} else {
		.value = newValue()
	}
	return .value
}

func valuePool( unsafe.Pointer) *sync.Pool {
	if  := valuePools.Load(uintptr());  != nil {
		return 
	}
	return valuePools.Store(uintptr(), &sync.Pool{})
}