package decoder

import (
	
	
	

	
)

type sliceDecoder struct {
	elemType reflect.Type
	// slicePtrType is the type descriptor of the pointer to the slice.
	slicePtrType unsafe.Pointer
	valueDecoder Decoder
	size         uintptr
	// bufPool holds the buffers into which the elements of a long array are decoded before its length is known
	// ( see decodeLong ). A buffer in the pool has only zero values, so that an element is decoded into a zero
	// value.
	bufPool    sync.Pool
	structName string
	fieldName  string
	// typ is the type of the slice, which the type errors report.
	typ reflect.Type
}

// If use reflect.SliceHeader, data type is uintptr.
// In this case, Go compiler cannot trace reference created by newArray().
// So, define using unsafe.Pointer as data type
type sliceHeader struct {
	data unsafe.Pointer
	len  int
	cap  int
}

// sliceBuf is a buffer of the elements of a slice, allocated and grown by reflect.Value.Grow,
// so that its memory has the type of the elements.
type sliceBuf struct {
	hdr sliceHeader
}

const (
	// inPlaceSliceLength is the number of the elements of an array which are decoded into the slice itself, if it
	// has no more capacity: most arrays are no longer, and the elements of a longer one are decoded into a buffer
	// from there, so that its slice is allocated once, of its length.
	inPlaceSliceLength = 64
	// defaultSliceCapacity is the capacity of a new buffer of the elements.
	defaultSliceCapacity = 4
)

func newSliceDecoder( Decoder,  reflect.Type,  uintptr, ,  string) *sliceDecoder {
	return &sliceDecoder{
		typ:          reflect.SliceOf(),
		valueDecoder: ,
		elemType:     ,
		slicePtrType: ptrTypeOf(reflect.SliceOf()),
		size:         ,
		bufPool: sync.Pool{
			New: func() any {
				return &sliceBuf{}
			},
		},
		structName: ,
		fieldName:  ,
	}
}

// sliceValue returns the reflect.Value of the slice whose header is at p.
func ( *sliceDecoder) ( *sliceHeader) reflect.Value {
	return valueAt(.slicePtrType, unsafe.Pointer())
}

// grow makes the capacity of the slice at dst n or more, keeping its first length elements, as append does.
func ( *sliceDecoder) ( *sliceHeader, ,  int) {
	if  <= .cap {
		return
	}
	.len = 
	if  < defaultSliceCapacity {
		 = defaultSliceCapacity
	}
	.sliceValue().Grow( - )
}

// decodeLong decodes the elements of the array from cursor, the one at index n, which follows the n elements
// decoded into the slice at dst, into a buffer whose length is not known yet, and stores them all into the slice,
// allocated once, of their length. It is not inlined, so that Decode keeps the size it had: most arrays are shorter.
//
//go:noinline
func ( *sliceDecoder) ( *RuntimeContext, ,  int64,  *sliceHeader,  int) (int64, error) {
	 := .Buf
	 := .takeBuf(, )
	 := 
	for {
		 := .bufElem(, )
		,  := .valueDecoder.Decode(, , , )
		if  != nil {
			.storeBuf(, , +1, +1)
			return 0, 
		}
		 = skipWhiteSpace(, )
		switch [] {
		case ']':
			.storeBuf(, , +1, +1)
			return  + 1, nil
		case ',':
			++
		default:
			.storeBuf(, , +1, +1)
			return 0, errors.ErrInvalidCharacter([], "slice", )
		}
		++
	}
}

// takeBuf takes a buffer of the pool, which the n elements decoded into the slice at dst are copied to.
func ( *sliceDecoder) ( *sliceHeader,  int) *sliceBuf {
	 := .bufPool.Get().(*sliceBuf)
	.growBuf(, 0, 2*)
	.hdr.len = 
	 := *
	.len = 
	reflect.Copy(.sliceValue(&.hdr), .sliceValue(&))
	return 
}

// bufElem returns the element of the buffer at idx, which follows the elements decoded into it. The buffer doubles,
// so that the slice which it becomes ( see storeBuf ) leaves little garbage.
func ( *sliceDecoder) ( *sliceBuf,  int) unsafe.Pointer {
	if  >= .hdr.cap {
		.growBuf(, , 2*+1)
	}
	return unsafe.Add(.hdr.data, uintptr()*.size)
}

// storeBuf stores the n elements of the buffer into the slice at dst, and puts the buffer back to the pool, with its
// first used elements, which were decoded into, whole or in part, cleared. The buffer becomes the slice, which has no
// room for the elements, instead of a copy of them: a long slice is not allocated twice, and the pool doesn't keep a
// buffer of its size. A buffer which the pool had from a longer slice, more than the doubling up to the elements ( with
// the rounding of its size ) leaves, is copied from instead, so that the slice keeps no more room than that.
func ( *sliceDecoder) ( *sliceHeader,  *sliceBuf, ,  int) {
	if .cap <  && .hdr.cap < 3* {
		* = .hdr
		.len = 
		.hdr = sliceHeader{}
		.bufPool.Put()
		return
	}
	.store(, , )
	.releaseBuf(, )
}

// growBuf makes the capacity of the buffer n or more, keeping its first length elements.
// The elements after them are zero values.
func ( *sliceDecoder) ( *sliceBuf, ,  int) {
	.grow(&.hdr, , )
}

// releaseBuf clears the first n elements of the buffer, which are all it may have used,
// and puts it back to the pool: it keeps nothing the decoded value refers to.
func ( *sliceDecoder) ( *sliceBuf,  int) {
	if  > 0 {
		.hdr.len = 
		.sliceValue(&.hdr).Clear()
	}
	.hdr.len = 0
	.bufPool.Put()
}

// store copies the n elements of the buffer to the slice at dst: into its array when it has room
// for them, or else into a new array of their length.
func ( *sliceDecoder) ( *sliceHeader,  *sliceBuf,  int) {
	if .cap <  {
		* = sliceHeader{}
		.sliceValue().Grow()
	}
	.len = 
	.hdr.len = 
	reflect.Copy(.sliceValue(), .sliceValue(&.hdr))
}

func ( *sliceDecoder) ( *RuntimeContext, ,  int64,  unsafe.Pointer) (int64, error) {
	 := .Buf
	for {
		switch [] {
		case ' ', '\n', '\t', '\r':
			++
			continue
		case 'n':
			if  := validateNull(, );  != nil {
				return 0, 
			}
			 += 4
			*(*sliceHeader)() = sliceHeader{}
			return , nil
		case '[':
			// only an array nests its values one level deeper: null or another value at the limit is not too deep
			++
			if  > maxDecodeNestingDepth {
				return 0, errors.ErrExceededMaxDepth([], )
			}
			++
			 = skipWhiteSpace(, )
			 := (*sliceHeader)()
			if [] == ']' {
				if .data == nil {
					.data = unsafe.Pointer(&zeroBase)
				} else {
					.len = 0
				}
				++
				return , nil
			}
			// The elements are decoded into the slice, which grows as append grows it: the elements of its array are
			// decoded into, the ones after its length too, as encoding/json does. The elements beyond its capacity
			// and inPlaceSliceLength are decoded into a buffer ( see decodeLong ).
			 := max(.cap, inPlaceSliceLength)
			 := 0
			for {
				if  ==  {
					return .decodeLong(, , , , )
				}
				.grow(, , +1)
				 := unsafe.Add(.data, uintptr()*.size)
				,  := .valueDecoder.Decode(, , , )
				if  != nil {
					.len =  + 1
					return 0, 
				}
				 = skipWhiteSpace(, )
				switch [] {
				case ']':
					.len =  + 1
					++
					return , nil
				case ',':
					++
				default:
					.len =  + 1
					return 0, errors.ErrInvalidCharacter([], "slice", )
				}
				++
			}
		default:
			return .decodeOther(, , )
		}
	}
}

// decodeOther skips the value at cursor, which is not an array: a value of another kind is a type error, and
// anything else a syntax error. It is a function of its own, so that Decode keeps the size it had.
//
//go:noinline
func ( *sliceDecoder) ( *RuntimeContext, ,  int64) (int64, error) {
	if isOtherValue(.Buf[], arrayValue) {
		return .skipTypeError(, , .typ)
	}
	return 0, errors.ErrUnexpectedEndOfJSON("slice", )
}

func ( *sliceDecoder) ( *RuntimeContext, ,  int64) ([][]byte, int64, error) {
	 := .Buf
	 := [][]byte{}
	for {
		switch [] {
		case ' ', '\n', '\t', '\r':
			++
			continue
		case 'n':
			if  := validateNull(, );  != nil {
				return nil, 0, 
			}
			 += 4
			return [][]byte{nullbytes}, , nil
		case '[':
			++
			if  > maxDecodeNestingDepth {
				return nil, 0, errors.ErrExceededMaxDepth([], )
			}
			++
			 = skipWhiteSpace(, )
			if [] == ']' {
				++
				return , , nil
			}
			 := 0
			for {
				, ,  := .Option.Path.node.Index()
				if  != nil {
					return nil, 0, 
				}
				if  {
					if  != nil {
						 := .Option.Path.node
						.Option.Path.node = 
						, ,  := .valueDecoder.DecodePath(, , )
						.Option.Path.node = 
						if ,  := .(*errors.PathError);  {
							if ,  := .(*PathIndexAllNode);  {
								// the rest of the path after [*] does not fit the element, so it selects nothing
								// in it
								 = nil
								,  = skipValue(, , )
							}
						}
						if  != nil {
							return nil, 0, 
						}
						 = append(, ...)
						 = 
					} else {
						 := 
						,  := skipValue(, , )
						if  != nil {
							return nil, 0, 
						}
						 = append(, [:])
						 = 
					}
				} else {
					,  := skipValue(, , )
					if  != nil {
						return nil, 0, 
					}
					 = 
				}
				 = skipWhiteSpace(, )
				switch [] {
				case ']':
					++
					return , , nil
				case ',':
					++
				default:
					return nil, 0, errors.ErrInvalidCharacter([], "slice", )
				}
				++
			}
		case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
			return nil, 0, &errors.UnmarshalTypeError{Value: "number", Type: .typ, Offset: }
		default:
			return nil, 0, errors.ErrUnexpectedEndOfJSON("slice", )
		}
	}
}