package decoder

import (
	
	
	
	
	

	
	
)

// AssignValue sets src, cast to the type which dst points to, to the value dst points to. dst must be a pointer which
// is not nil. The value is not changed when src cannot be cast.
func (,  reflect.Value) error {
	if .Kind() != reflect.Ptr || .IsNil() {
		var  reflect.Type
		if .IsValid() {
			 = .Type()
		}
		return &errors.InvalidUnmarshalError{Type: }
	}
	return assignValue(.Elem(), , &visits{})
}

// pathDepthBeforeCycles is how many objects and arrays ( maps, slices, arrays and structs ), or pointers in a row, a
// cast or a recursive descent goes into before it records them to find a cycle: 1000, the startDetectingCyclesAfter
// of encoding/json, so that a value which is not that deep costs no record. It only delays the error of a cycle.
const pathDepthBeforeCycles = 1000

// pathMaxDepth is how many objects and arrays ( maps, slices, arrays and structs ) a cast or a recursive descent goes
// into at most, past which it returns an error instead of exhausting the stack: the levels of a value which
// encoding/json decodes and encodes, maxDecodeNestingDepth, in the slice of such values which Path.Unmarshal casts.
// The pointers and interfaces which lead from one to the next are followed in a loop, not deeper, and a struct
// embedded in another by its value with no name in its tag, which Marshal writes in the object of the other, is gone
// through as a part of it ( it is as deep as its type at most ).
const pathMaxDepth = maxDecodeNestingDepth + 1

// visit is a value which a cast or a recursive descent is inside of, by its address and type.
type visit struct {
	ptr unsafe.Pointer
	typ reflect.Type
	len int
}

// visits are the objects and arrays which a cast or a recursive descent is inside of, so that it stops with an error
// at a value which holds itself, which has no end, or which is nested deeper than pathMaxDepth. A value which holds
// itself does so through a map, a slice, or a pointer to an array or a struct, which is in a cycle with it.
type visits struct {
	depth int
	seen  map[visit]struct{}
}

// containerVisit returns the visit of v, an object or an array, or false if v cannot be in a cycle: a nil or empty map
// or slice, or an array or struct which has no address, as no pointer leads to it.
func containerVisit( reflect.Value) (visit, bool) {
	switch .Kind() {
	case reflect.Map:
		return visit{ptr: .UnsafePointer(), typ: .Type()}, !.IsNil()
	case reflect.Slice:
		return visit{ptr: .UnsafePointer(), typ: .Type(), len: .Len()}, .Len() != 0
	}
	if !.CanAddr() {
		return visit{}, false
	}
	return visit{ptr: .Addr().UnsafePointer(), typ: .Type()}, true
}

// enter records that a cast or a recursive descent goes into v, an object or an array, and returns an error if it is
// inside of v already, as v holds itself, or past pathMaxDepth. leave records that it leaves v again.
func ( *visits) ( reflect.Value) error {
	.depth++
	if .depth <= pathDepthBeforeCycles {
		return nil
	}
	if .depth > pathMaxDepth {
		return &errors.UnsupportedValueError{Value: , Str: "exceeded max depth"}
	}
	,  := containerVisit()
	if ! {
		return nil
	}
	if ,  := .seen[];  {
		if .Kind() == reflect.Array || .Kind() == reflect.Struct {
			// the cycle goes through a pointer to it, which Marshal names too
			return errCycle(.Addr())
		}
		return errCycle()
	}
	if .seen == nil {
		.seen = map[visit]struct{}{}
	}
	.seen[] = struct{}{}
	return nil
}

func ( *visits) ( reflect.Value) {
	if .depth > pathDepthBeforeCycles {
		if ,  := containerVisit();  {
			delete(.seen, )
		}
	}
	.depth--
}

// pointerVisits are the pointers which a value leads through, one after the other, to the value it holds, so that a
// pointer which leads back to itself, with no object or array between ( type P *P, or an interface which holds a
// pointer to itself ), stops with an error.
type pointerVisits struct {
	count int
	seen  map[visit]struct{}
}

// follow records that v, a pointer which is not nil, is followed, and returns an error if it was before.
func ( *pointerVisits) ( reflect.Value) error {
	.count++
	if .count <= pathDepthBeforeCycles {
		return nil
	}
	 := visit{ptr: .UnsafePointer(), typ: .Type()}
	if ,  := .seen[];  {
		return errCycle()
	}
	if .seen == nil {
		.seen = map[visit]struct{}{}
	}
	.seen[] = struct{}{}
	return nil
}

func errCycle( reflect.Value) error {
	return &errors.UnsupportedValueError{Value: , Str: fmt.Sprintf("encountered a cycle via %s", .Type())}
}

// assignValue sets v, cast to the type of dst, to dst, which can be set. A null v, the zero Value or a nil pointer or
// interface, as JSON null is decoded to, is cast to the zero value. dst is not changed when v cannot be cast: a
// value which holds others is made whole before it is set.
func assignValue(,  reflect.Value,  *visits) error {
	var  pointerVisits
	for {
		switch .Kind() {
		case reflect.Invalid:
			.SetZero()
			return nil
		case reflect.Ptr, reflect.Interface:
			if .IsNil() {
				.SetZero()
				return nil
			}
		}
		if isScalarKind(.Kind()) {
			// a value of another kind is not assignable to a scalar: a scalar is cast to it, and assignInside reaches
			// one in the rest
			if isScalarKind(.Kind()) {
				return assignScalar(, )
			}
		} else if  := .Type(); .Kind() != reflect.Map && .Type().AssignableTo() {
			// a map is copied by assignMap
			.Set()
			return nil
		}
		if .Kind() == reflect.Interface {
			 = .Elem()
			continue
		}
		if .Kind() == reflect.Ptr {
			return assignPointer(, , )
		}
		if .Kind() != reflect.Ptr {
			break
		}
		if  := .follow();  != nil {
			return 
		}
		 = .Elem()
	}
	switch .Kind() {
	case reflect.Map, reflect.Slice, reflect.Array, reflect.Struct:
		if  := .enter();  != nil {
			return 
		}
		 := assignInside(, , )
		.leave()
		return 
	}
	return assignInside(, , )
}

// assignPointer is assignValue to dst, a pointer, of v, which is not null, nor an interface, nor assignable to dst:
// what dst points to is allocated, and v is cast to it.
func assignPointer(,  reflect.Value,  *visits) error {
	 := .Type()
	if !pointerTypesTake(, .Type()) {
		return fmt.Errorf("failed to cast to %s from %s", , .Type())
	}
	 := reflect.New(.Elem())
	if  := assignValue(.Elem(), , );  != nil {
		return 
	}
	.Set()
	return nil
}

// pointerTypesTake reports whether a value of the type vt is cast to the pointer type t: whether, of the types which t
// leads to, each one pointing to the next, one takes vt as it is, or is not a pointer, before they come back to one
// of them. A pointer type which leads back to itself ( type P *P ) takes nothing else but nil.
func pointerTypesTake(,  reflect.Type) bool {
	var  [4]reflect.Type
	 := [:0]
	for .Kind() == reflect.Ptr {
		if slices.Contains(, ) {
			return false
		}
		 = append(, )
		 = .Elem()
		if .Kind() != reflect.Map && .AssignableTo() {
			return true
		}
	}
	return true
}

// assignInside is assignValue of a v which is not null, nor a pointer or an interface, nor assigned as it is, to a
// dst which is not a pointer.
func assignInside(,  reflect.Value,  *visits) error {
	if isScalarKind(.Kind()) {
		if .Kind() == reflect.Array || .Kind() == reflect.Slice {
			// the first element is cast
			if .Len() == 0 {
				return fmt.Errorf("failed to cast to %s from empty %s", .Type(), .Kind())
			}
			return assignValue(, .Index(0), )
		}
		return assignScalar(, )
	}
	switch .Kind() {
	case reflect.Array:
		return assignArray(, , )
	case reflect.Slice:
		return assignSlice(, , )
	case reflect.Map:
		return assignMap(, , )
	case reflect.Struct:
		return assignStruct(, , )
	}
	return fmt.Errorf("failed to cast to %s from %s", .Type(), .Type())
}

// isScalarKind reports whether a value of the kind is a number, a string or a bool, which assignScalar casts to.
func isScalarKind( reflect.Kind) bool {
	switch  {
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
		reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr,
		reflect.Float32, reflect.Float64, reflect.String, reflect.Bool:
		return true
	}
	return false
}

// assignScalar sets v, which is not an array or a slice, cast to the kind of dst, a number, a string or a bool.
func assignScalar(,  reflect.Value) error {
	switch .Kind() {
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		,  := castInt()
		if  != nil {
			return 
		}
		.SetInt()
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		,  := castUint()
		if  != nil {
			return 
		}
		.SetUint()
	case reflect.Float32, reflect.Float64:
		,  := castFloat()
		if  != nil {
			return 
		}
		.SetFloat()
	case reflect.String:
		,  := castString()
		if  != nil {
			return 
		}
		if .Type() == jsonNumberType && !jsonnum.IsValid([]byte()) {
			// a json.Number is a number of JSON
			return fmt.Errorf("failed to cast to json.Number from %q", )
		}
		.SetString()
	default:
		,  := castBool()
		if  != nil {
			return 
		}
		.SetBool()
	}
	return nil
}

func castInt( reflect.Value) (int64, error) {
	switch .Kind() {
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return .Int(), nil
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		return int64(.Uint()), nil
	case reflect.String:
		return strconv.ParseInt(.String(), 10, 64)
	case reflect.Bool:
		if .Bool() {
			return 1, nil
		}
		return 0, nil
	case reflect.Float32, reflect.Float64:
		return int64(.Float()), nil
	}
	return 0, fmt.Errorf("failed to cast to int64 from %s", .Kind())
}

func castUint( reflect.Value) (uint64, error) {
	switch .Kind() {
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return uint64(.Int()), nil
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		return .Uint(), nil
	case reflect.String:
		return strconv.ParseUint(.String(), 10, 64)
	case reflect.Bool:
		if .Bool() {
			return 1, nil
		}
		return 0, nil
	case reflect.Float32, reflect.Float64:
		return uint64(.Float()), nil
	}
	return 0, fmt.Errorf("failed to cast to uint64 from %s", .Kind())
}

func castString( reflect.Value) (string, error) {
	switch .Kind() {
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return fmt.Sprint(.Int()), nil
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		return fmt.Sprint(.Uint()), nil
	case reflect.String:
		return .String(), nil
	case reflect.Bool:
		if .Bool() {
			return "true", nil
		}
		return "false", nil
	case reflect.Float32, reflect.Float64:
		return fmt.Sprint(.Float()), nil
	}
	return "", fmt.Errorf("failed to cast to string from %s", .Kind())
}

func castBool( reflect.Value) (bool, error) {
	switch .Kind() {
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		switch .Int() {
		case 0:
			return false, nil
		case 1:
			return true, nil
		}
		return false, fmt.Errorf("failed to cast to bool from %d", .Int())
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		switch .Uint() {
		case 0:
			return false, nil
		case 1:
			return true, nil
		}
		return false, fmt.Errorf("failed to cast to bool from %d", .Uint())
	case reflect.String:
		return strconv.ParseBool(.String())
	case reflect.Bool:
		return .Bool(), nil
	case reflect.Float32, reflect.Float64:
		switch .Float() {
		case 0:
			return false, nil
		case 1:
			return true, nil
		}
		return false, fmt.Errorf("failed to cast to bool from %f", .Float())
	}
	return false, fmt.Errorf("failed to cast to bool from %s", .Kind())
}

func castFloat( reflect.Value) (float64, error) {
	switch .Kind() {
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return float64(.Int()), nil
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		return float64(.Uint()), nil
	case reflect.String:
		return strconv.ParseFloat(.String(), 64)
	case reflect.Bool:
		if .Bool() {
			return 1, nil
		}
		return 0, nil
	case reflect.Float32, reflect.Float64:
		return .Float(), nil
	}
	return 0, fmt.Errorf("failed to cast to float64 from %s", .Kind())
}

func assignArray(,  reflect.Value,  *visits) error {
	if .Kind() != reflect.Slice && .Kind() != reflect.Array {
		return fmt.Errorf("failed to cast to array from %s", .Kind())
	}
	if .Len() != .Len() {
		return fmt.Errorf("failed to cast [%d]array from slice of %d length", .Len(), .Len())
	}
	 := reflect.New(.Type()).Elem()
	for  := 0;  < .Len(); ++ {
		if  := assignValue(.Index(), .Index(), );  != nil {
			return 
		}
	}
	.Set()
	return nil
}

func assignSlice(,  reflect.Value,  *visits) error {
	if .Kind() != reflect.Slice && .Kind() != reflect.Array {
		return fmt.Errorf("failed to cast to slice from %s", .Kind())
	}
	 := reflect.MakeSlice(.Type(), .Len(), .Len())
	for  := 0;  < .Len(); ++ {
		if  := assignValue(.Index(), .Index(), );  != nil {
			return 
		}
	}
	.Set()
	return nil
}

func assignMap(,  reflect.Value,  *visits) error {
	switch .Kind() {
	case reflect.Map:
		 := .Type()
		 := reflect.MakeMap()
		// SetMapIndex copies the key and the value, and assignValue sets all of them, so they are reused
		 := reflect.New(.Key()).Elem()
		 := reflect.New(.Elem()).Elem()
		 := .MapRange()
		for .Next() {
			if  := assignValue(, .Key(), );  != nil {
				return 
			}
			if  := assignValue(, .Value(), );  != nil {
				return 
			}
			.SetMapIndex(, )
		}
		.Set()
		return nil
	case reflect.Slice:
		if .Len() > 0 {
			return assignValue(, .Index(0), )
		}
		return fmt.Errorf("failed to cast to map from empty slice")
	}
	return fmt.Errorf("failed to cast to map from %s", .Kind())
}

func assignStruct(,  reflect.Value,  *visits) error {
	switch .Kind() {
	case reflect.Map:
		 := reflect.New(.Type()).Elem()
		 := reflect.New(stringType).Elem()
		 := .MapRange()
		for .Next() {
			if  := assignValue(, .Key(), );  != nil {
				return 
			}
			if  := setStructField(, .String(), .Value(), );  != nil {
				return 
			}
		}
		.Set()
		return nil
	case reflect.Struct:
		 := reflect.New(.Type()).Elem()
		 := .Type()
		for  := 0;  < .NumField(); ++ {
			if !.Field().IsExported() {
				// the value of an unexported field cannot be read
				continue
			}
			if  := setStructField(, .Field().Name, .Field(), );  != nil {
				return 
			}
		}
		.Set()
		return nil
	case reflect.Slice:
		if .Len() > 0 {
			return assignValue(, .Index(0), )
		}
		return fmt.Errorf("failed to cast to struct from empty slice")
	}
	return fmt.Errorf("failed to cast to struct from %s", .Kind())
}

// setStructField sets v, cast, to the field of the struct ret which has the name, if ret has one which can be set:
// an exported field, which is not promoted through a pointer to an unexported struct type. A struct which is embedded
// by a pointer of an exported type on the way to the field is allocated.
func setStructField( reflect.Value,  string,  reflect.Value,  *visits) error {
	,  := .Type().FieldByName()
	if ! || !.IsExported() {
		return nil
	}
	 := 
	for ,  := range .Index {
		if  > 0 && .Kind() == reflect.Ptr {
			if .IsNil() {
				if !.CanSet() {
					return nil
				}
				.Set(reflect.New(.Type().Elem()))
			}
			 = .Elem()
		}
		 = .Field()
	}
	if !.CanSet() {
		return nil
	}
	return assignValue(, , )
}