package jsontext

import (
	
	
	

	
	
)

// maxDepth is the deepest nesting of objects and arrays which an encoder or decoder takes.
const maxDepth = 10000

// level is a level of the nesting: the top level of the stream, or an open object or array. Its count is the
// number of tokens in it: the values of the top level or an array, and the names and values of an object.
type level struct {
	count  int64
	object bool
	first  int    // for an object, the index in names.ends of its first name
	last   int    // for an object, the index in names.ends of its last name, or -1, or, for valueScanner.lazyNames, -2 minus the position of the name in the input
	named  int64  // for an object, its count after its last name was added
	bits   uint64 // for an object, the bits of its names ( jsonstring.NameBit ), which the name of no bit is not one of
}

// stack is the state of the grammar: the levels of the nesting, the top level first, and the names of the open
// objects.
type stack struct {
	levels []level
	names  names
	// outer gives the levels around the level outerDepth, an encoder was attached at with the count outerCount,
	// which the stack doesn't have ( see textcoder.Attach ): the pointers and the levels of the stack are found
	// with them ( see full ).
	outer      textcoder.Outer
	outerDepth int
	outerCount int64
	// base is the number of the levels around the top level of the stack in the whole output, of an encoder attached
	// in them, which its depth is counted after for the deepest level ( see textcoder.Attachment.OuterDepth ).
	base int
}

// full returns the stack of the whole output: the levels which outer gives, in place of the levels up to
// outerDepth, followed by the levels in them. It is made for a pointer or for the levels which an encoder is asked
// for, which most writes don't need.
func ( *stack) () *stack {
	 := &stack{}
	.reset()
	.applyLevels(.outer.Levels())
	,  := &.levels[.outerDepth], .last()
	 := .count - .outerCount
	if len(.levels) > .outerDepth+1 {
		-- // the open value of the next level, which its push below counts again
	}
	.count += 
	if .object && .last >= .first {
		// the names written after the attach.
		for  := .first;  <= .last; ++ {
			.insertName(.names.get(), false)
		}
		.named = .named + 
	}
	 := .levels[.outerDepth+1:]
	for ,  := range  {
		_ = .push(.object)
		if  > 0 {
			// the open value, which the push counted again in the level before
			.levels[len(.levels)-2].count = [-1].count
		}
		 := .last()
		if .object && .last >= .first {
			for  := .first;  <= .last; ++ {
				.insertName(.names.get(), false)
			}
		}
		.count, .named = .count, .named
	}
	return 
}

// applyLevels sets the stack, which has the top level only, to the levels, the top level first, of which an
// object has its last name only ( see textcoder.Level ).
func ( *stack) ( []textcoder.Level) {
	for ,  := range  {
		if  > 0 {
			// the open value of the level which contains it is counted by the push.
			_ = .push(.Object)
		}
		 := .last()
		if .Object && .Name != nil {
			// the name of the value which is open or next, the place of the value: the names before it are not
			// given, which a value written at its place can't have.
			.insertName(.Name, false)
			.named = (.Count - 1) | 1 // the count after the name
		}
		.count = .Count
	}
}

// own gives the stack arrays of its own: the ones of a coder which was copied are shared with the coder it was
// copied from, whose state they hold too. The indexes of the names are made again where an object needs one.
// If the other coder changed the arrays since the copy, which interleaved use of both does, the names may not
// fit the levels: they are made again then, as empty names where the levels need one, so that the copy, whose
// reads or writes are not defined, keeps a state which doesn't panic.
func ( *stack) () {
	.levels = slices.Clone(.levels)
	.names.buf = slices.Clone(.names.buf)
	.names.ends = slices.Clone(.names.ends)
	.names.indexes = nil
	if !.namesFit() {
		.refit()
	}
}

// namesFit reports whether the levels and the names are in the state which reads and writes keep: an object
// which is not the deepest level has the name of the value which is open in it, its last one; the names of an
// object follow the ones of the object around it; and the deepest object has its last name, if it has one, at
// the end of the names.
func ( *stack) () bool {
	 := &.names
	for ,  := range .ends {
		if  > len(.buf) ||  > 0 &&  < .ends[-1] {
			return false
		}
	}
	if len(.levels) == 0 || .levels[0].object {
		return false
	}
	 := 0 // the index of the first name of the next object
	 := len(.levels) - 1
	for ,  := range .levels {
		if !.object {
			continue
		}
		if .first !=  {
			return false
		}
		if  <  {
			// its name and the value which is open in it are counted
			if .count%2 == 1 || .count == 0 || .last < .first || .last >= len(.ends) {
				return false
			}
			 = .last + 1
			continue
		}
		// the deepest level, which has no name before its first member
		if .last == -1 {
			return .count == 0 && len(.ends) == .first
		}
		return .last >= .first && .last == len(.ends)-1
	}
	return len(.ends) == 
}

// refit makes the names again for the levels, which namesFit takes: an object which is not the deepest level, or
// which has members, has an empty name.
func ( *stack) () {
	 := &.names
	.buf, .ends = .buf[:0], .ends[:0]
	.levels[0].object = false
	for  := range .levels {
		 := &.levels[]
		if !.object {
			continue
		}
		.first, .last, .named, .bits = len(.ends), -1, 0, 0
		if  < len(.levels)-1 {
			.count = max(.count&^1, 2) // its name and the value which is open in it
		}
		if .count > 0 {
			.ends = append(.ends, len(.buf))
			.last, .named = .first, (.count-1)|1 // the count after the name, before its value
		}
	}
}

func ( *stack) () {
	.levels = append(.levels[:0], level{})
	.base = 0
	.names.reset()
}

// depth is the number of open objects and arrays.
func ( *stack) () int { return len(.levels) - 1 }

func ( *stack) () *level { return &.levels[len(.levels)-1] }

// push opens an object or an array, whose begin token is a value of the level where it is.
func ( *stack) ( bool) error {
	 := len(.levels) // once, which keeps the function inlined into the reads and the writes of tokens
	if +.base > maxDepth {
		return errMaxDepth
	}
	.levels[-1].count++
	if  < cap(.levels) {
		.levels = .levels[:+1]
	} else {
		.grow()
	}
	// the level is written in place: an append of it would build it in a temporary, whose copy would load it
	// by 16 bytes from narrower stores, which stalls the CPU.
	*.last() = level{object: , first: len(.names.ends), last: -1}
	return nil
}

func ( *stack) () { .levels = append(.levels, level{}) }

// pop closes the innermost object or array.
func ( *stack) () {
	if  := .last(); .object {
		.names.truncate(.first)
	}
	.levels = .levels[:len(.levels)-1]
}

// Where the innermost level is in its grammar.
func ( *level) () bool  { return .object && .count%2 == 0 }
func ( *level) () bool { return .object && .count%2 == 1 }

// The pointers of a stack point to a value in the innermost level: pointLast to the last one which was read or
// written, pointNext to the one after it where a value is next, and pointAt to the level itself, or to the
// value of the last name in an object whose value is next.
const (
	pointLast = iota
	pointNext
	pointAt
	pointOut  // pointAt of the level which contains the innermost one, as if it was closed
	pointHere // the innermost object or array itself
)

// pointer is the JSON pointer of the stack at the value which where chooses.
func ( *stack) ( int) Pointer {
	if .outer != nil {
		return .full().()
	}
	if len(.levels) == 1 {
		return ""
	}
	return Pointer(.pointerBytes(, 0))
}

// namePointer is the pointer to the name of a member of the innermost object, which is not inserted.
func ( *stack) ( []byte) Pointer {
	if .outer != nil {
		return .full().()
	}
	return Pointer(appendPointerToken(.pointerBytes(pointAt, 0), ))
}

// pointerBytes is the pointer of the place where, of the levels after the level of the depth from.
func ( *stack) (,  int) []byte {
	var  []byte
	 := len(.levels)
	switch  {
	case pointOut:
		--
		 = pointAt
	case pointHere:
		--
		 = pointLast
	}
	for  :=  + 1;  < ; ++ {
		 := &.levels[]
		 :=  == -1
		switch {
		case .object:
			// the last name, while its value or a value in it is read, and after it was read if pointLast.
			// the name must be the one of the last member, which a value where a name is has not.
			if .last >= 0 && .named >= .count-1 && (.count%2 == 1 || ! ||  == pointLast) {
				 = appendPointerToken(, .names.get(.last))
			}
		case ! ||  == pointLast:
			if .count > 0 {
				 = strconv.AppendInt(append(, '/'), .count-1, 10)
			}
		case  == pointNext:
			 = strconv.AppendInt(append(, '/'), .count, 10)
		}
	}
	return 
}

// insertName adds the unquoted name to the innermost object, which must need a name, and reports false if
// rejectDuplicate is set and the object has it already. Without rejectDuplicate, the object keeps only its last
// name, which the pointers need.
func ( *stack) ( []byte,  bool) bool {
	 := .last()
	 := &.names
	if ! {
		// the object keeps its last name only, for the pointers of errors: no object is indexed.
		.buf = append(.buf[:.start(.first)], ...)
		.ends = append(.ends[:.first], len(.buf))
		.last = .first
		.named = .count + 1
		return true
	}
	if  := jsonstring.NameBit(); .bits& == 0 {
		.bits |=  // a name of a bit which no name has is new: it is not looked for
	} else if .has(.first, ) {
		return false
	}
	.add(.first, )
	.last = len(.ends) - 1
	.named = .count + 1
	return true
}

// addNewName adds the unquoted name to the innermost object, which must need a name, as insertName with
// rejectDuplicate does, and reports true, if the name is of a bit which no name of the object has and the names of
// the objects are few, as most are: then it is new, and no object has an index of its names. Otherwise it adds
// nothing, and insertName is to add it.
func ( *stack) ( []byte) bool {
	 := &.levels[len(.levels)-1]
	 := &.names
	 := jsonstring.NameBit()
	if .bits& != 0 || len(.indexes) != 0 || len(.ends)-.first >= maxLinearNames || len(.buf)+len() > maxLinearBytes {
		return false
	}
	.bits |= 
	.buf = append(.buf, ...)
	.ends = append(.ends, len(.buf))
	.last = len(.ends) - 1
	.named = .count + 1
	return true
}

// names are the names of the open objects, back to back, an object after the objects which contain it.
type names struct {
	buf  []byte // the names, unquoted
	ends []int  // the end of each name in buf
	// the indexes of the objects of many names, the innermost last.
	indexes []nameIndex
}

// A name is looked for in the names of its object one by one while they are few, and over maxLinearNames or
// maxLinearBytes of them, through an index of their hashes: the limits over which encoding/json/jsontext takes
// a map.
const (
	maxLinearNames = 64
	maxLinearBytes = 1024
)

// nameIndex is an index of the names of an object: a table of open addressing, whose size is a power of two,
// of the positions of its names plus one, by their hashes.
type nameIndex struct {
	first  int // the index in ends of the first name of the object
	slots  []int32
	hashes []uint64 // the hash of each name of the object
}

// nameSeed is the seed of the hashes, chosen at random as the one of a Go map is, so that no input can have
// many names of the same hash.
var nameSeed = maphash.MakeSeed()

func ( *names) () {
	.buf = .buf[:0]
	.ends = .ends[:0]
	.indexes = .indexes[:0]
}

// truncate drops the names from the index first on: the names of an object which is closed, or of the objects
// which a scan that gave up added, whose indexes are dropped too.
func ( *names) ( int) {
	 := len(.indexes)
	for  > 0 && .indexes[-1].first >=  {
		--
	}
	.indexes = .indexes[:]
	.buf = .buf[:.start()]
	.ends = .ends[:]
}

// start is the position in buf of the name at the index i.
func ( *names) ( int) int {
	if  == 0 {
		return 0
	}
	return .ends[-1]
}

func ( *names) ( int) []byte { return .buf[.start():.ends[]] }

// index is the index of the object whose first name is at first, or nil.
func ( *names) ( int) *nameIndex {
	if  := len(.indexes);  > 0 && .indexes[-1].first ==  {
		return &.indexes[-1]
	}
	return nil
}

// has reports whether the object whose first name is at first has the name.
func ( *names) ( int,  []byte) bool {
	if  := .index();  != nil {
		 := maphash.Bytes(nameSeed, )
		 := uint64(len(.slots) - 1)
		for  :=  & ; .slots[] != 0;  = ( + 1) &  {
			 := int(.slots[]) - 1
			if .hashes[] ==  && string(.get(+)) == string() {
				return true
			}
		}
		return false
	}
	// the length and the first byte are compared first, which rejects most names without a call of the runtime.
	 := .start()
	for ,  := range .ends[:] {
		if - == len() && (len() == 0 || .buf[] == [0] && string(.buf[:]) == string()) {
			return true
		}
		 = 
	}
	return false
}

// add appends a name to the innermost object, whose first name is at first.
func ( *names) ( int,  []byte) {
	.buf = append(.buf, ...)
	.ends = append(.ends, len(.buf))
	if len(.indexes) == 0 && len(.ends)- <= maxLinearNames && len(.buf) <= maxLinearBytes {
		return // no object has an index, nor needs one: the names of all of them are few
	}
	if  := .index();  != nil {
		.hashes = append(.hashes, maphash.Bytes(nameSeed, ))
		if 2*len(.hashes) > len(.slots) {
			.rebuild(2 * len(.slots))
		} else {
			.insert(len(.hashes) - 1)
		}
		return
	}
	if len(.ends)- > maxLinearNames || len(.buf)-.start() > maxLinearBytes {
		.indexObject()
	}
}

// indexObject makes the index of the names of the innermost object, whose first name is at first.
func ( *names) ( int) {
	// the arrays of an index of an object which was closed are used again.
	if  := len(.indexes);  < cap(.indexes) {
		.indexes = .indexes[:+1]
	} else {
		.indexes = append(.indexes, nameIndex{})
	}
	 := &.indexes[len(.indexes)-1]
	.first, .hashes = , .hashes[:0]
	for  := ;  < len(.ends); ++ {
		.hashes = append(.hashes, maphash.Bytes(nameSeed, .get()))
	}
	// a table of a quarter of its slots used at most: an object of a copy, whose indexes were dropped, may have
	// many names already.
	 := 4 * maxLinearNames
	for 2*len(.hashes) >  {
		 *= 2
	}
	.rebuild()
}

// rebuild makes the table of the given size, a power of two, of all the names.
func ( *nameIndex) ( int) {
	if cap(.slots) >=  {
		.slots = .slots[:]
		clear(.slots)
	} else {
		.slots = make([]int32, )
	}
	for  := range .hashes {
		.insert()
	}
}

// insert puts the name at the index i of the object in the table.
func ( *nameIndex) ( int) {
	 := uint64(len(.slots) - 1)
	 := .hashes[] & 
	for .slots[] != 0 {
		 = ( + 1) & 
	}
	.slots[] = int32( + 1)
}