package thrift

import (
	
	
	
	
	
	
)

// Unmarshal deserializes the thrift data from b to v using to the protocol p.
//
// The function errors if the data in b does not match the type of v.
//
// The function panics if v cannot be converted to a thrift representation.
//
// As an optimization, the value passed in v may be reused across multiple calls
// to Unmarshal, allowing the function to reuse objects referenced by pointer
// fields of struct values. When reusing objects, the application is responsible
// for resetting the state of v before calling Unmarshal again.
func ( Protocol,  []byte,  interface{}) error {
	 := bytes.NewReader()
	 := .NewReader()

	if  := NewDecoder().Decode();  != nil {
		return 
	}

	if  := .Len();  != 0 {
		return fmt.Errorf("unexpected trailing bytes at the end of thrift input: %d", )
	}

	return nil
}

type Decoder struct {
	r Reader
	f flags
}

func ( Reader) *Decoder {
	return &Decoder{r: , f: decoderFlags()}
}

func ( *Decoder) ( interface{}) error {
	 := reflect.TypeOf()
	 := reflect.ValueOf()

	if .Kind() != reflect.Ptr {
		panic("thrift.(*Decoder).Decode: expected pointer type but got " + .String())
	}

	 = .Elem()
	 = .Elem()

	,  := decoderCache.Load().(map[typeID]decodeFunc)
	,  := [makeTypeID()]

	if  == nil {
		 = decodeFuncOf(, make(decodeFuncCache))

		 := make(map[typeID]decodeFunc, len()+1)
		[makeTypeID()] = 
		for ,  := range  {
			[] = 
		}

		decoderCache.Store()
	}

	return (.r, , .f)
}

func ( *Decoder) ( Reader) {
	.r = 
	.f = .f.without(protocolFlags).with(decoderFlags())
}

func ( *Decoder) ( bool) {
	if  {
		.f = .f.with(strict)
	} else {
		.f = .f.without(strict)
	}
}

func decoderFlags( Reader) flags {
	return flags(.Protocol().Features() << featuresBitOffset)
}

var decoderCache atomic.Value // map[typeID]decodeFunc

type decodeFunc func(Reader, reflect.Value, flags) error

type decodeFuncCache map[reflect.Type]decodeFunc

func decodeFuncOf( reflect.Type,  decodeFuncCache) decodeFunc {
	 := []
	if  != nil {
		return 
	}
	switch .Kind() {
	case reflect.Bool:
		 = decodeBool
	case reflect.Int8:
		 = decodeInt8
	case reflect.Int16:
		 = decodeInt16
	case reflect.Int32:
		 = decodeInt32
	case reflect.Int64, reflect.Int:
		 = decodeInt64
	case reflect.Float32, reflect.Float64:
		 = decodeFloat64
	case reflect.String:
		 = decodeString
	case reflect.Slice:
		if .Elem().Kind() == reflect.Uint8 { // []byte
			 = decodeBytes
		} else {
			 = decodeFuncSliceOf(, )
		}
	case reflect.Map:
		 = decodeFuncMapOf(, )
	case reflect.Struct:
		 = decodeFuncStructOf(, )
	case reflect.Ptr:
		 = decodeFuncPtrOf(, )
	default:
		panic("type cannot be decoded in thrift: " + .String())
	}
	[] = 
	return 
}

func decodeBool( Reader,  reflect.Value,  flags) error {
	,  := .ReadBool()
	if  != nil {
		return 
	}
	.SetBool()
	return nil
}

func decodeInt8( Reader,  reflect.Value,  flags) error {
	,  := .ReadInt8()
	if  != nil {
		return 
	}
	.SetInt(int64())
	return nil
}

func decodeInt16( Reader,  reflect.Value,  flags) error {
	,  := .ReadInt16()
	if  != nil {
		return 
	}
	.SetInt(int64())
	return nil
}

func decodeInt32( Reader,  reflect.Value,  flags) error {
	,  := .ReadInt32()
	if  != nil {
		return 
	}
	.SetInt(int64())
	return nil
}

func decodeInt64( Reader,  reflect.Value,  flags) error {
	,  := .ReadInt64()
	if  != nil {
		return 
	}
	.SetInt(int64())
	return nil
}

func decodeFloat64( Reader,  reflect.Value,  flags) error {
	,  := .ReadFloat64()
	if  != nil {
		return 
	}
	.SetFloat()
	return nil
}

func decodeString( Reader,  reflect.Value,  flags) error {
	,  := .ReadString()
	if  != nil {
		return 
	}
	.SetString()
	return nil
}

func decodeBytes( Reader,  reflect.Value,  flags) error {
	,  := .ReadBytes()
	if  != nil {
		return 
	}
	.SetBytes()
	return nil
}

func decodeFuncSliceOf( reflect.Type,  decodeFuncCache) decodeFunc {
	 := .Elem()
	 := TypeOf()
	 := decodeFuncOf(, )

	return func( Reader,  reflect.Value,  flags) error {
		,  := .ReadList()
		if  != nil {
			return 
		}

		// Sometimes the list type is set to TRUE when the list contains only
		// TRUE values. Thrift does not seem to optimize the encoding by
		// omitting the boolean values that are known to all be TRUE, we still
		// need to decode them.
		switch .Type {
		case TRUE:
			.Type = BOOL
		}

		// TODO: implement type conversions?
		if  != .Type {
			if .have(strict) {
				return &TypeMismatch{item: "list item", Expect: , Found: .Type}
			}
			return nil
		}

		.Set(reflect.MakeSlice(, int(.Size), int(.Size)))
		 = .only(decodeFlags)

		for  := 0;  < int(.Size); ++ {
			if  := (, .Index(), );  != nil {
				return with(dontExpectEOF(), &decodeErrorList{cause: , index: })
			}
		}

		return nil
	}
}

func decodeFuncMapOf( reflect.Type,  decodeFuncCache) decodeFunc {
	,  := .Key(), .Elem()
	if .Size() == 0 { // map[?]struct{}
		return decodeFuncMapAsSetOf(, )
	}

	 := reflect.MapOf(, )
	 := reflect.Zero()
	 := reflect.Zero()
	 := TypeOf()
	 := TypeOf()
	 := decodeFuncOf(, )
	 := decodeFuncOf(, )

	return func( Reader,  reflect.Value,  flags) error {
		,  := .ReadMap()
		if  != nil {
			return 
		}

		.Set(reflect.MakeMapWithSize(, int(.Size)))

		if .Size == 0 { // empty map
			return nil
		}

		// TODO: implement type conversions?
		if  != .Key {
			if .have(strict) {
				return &TypeMismatch{item: "map key", Expect: , Found: .Key}
			}
			return nil
		}

		if  != .Value {
			if .have(strict) {
				return &TypeMismatch{item: "map value", Expect: , Found: .Value}
			}
			return nil
		}

		 := reflect.New().Elem()
		 := reflect.New().Elem()
		 = .only(decodeFlags)

		for  := 0;  < int(.Size); ++ {
			if  := (, , );  != nil {
				return with(dontExpectEOF(), &decodeErrorMap{cause: , index: })
			}
			if  := (, , );  != nil {
				return with(dontExpectEOF(), &decodeErrorMap{cause: , index: })
			}
			.SetMapIndex(, )
			.Set()
			.Set()
		}

		return nil
	}
}

func decodeFuncMapAsSetOf( reflect.Type,  decodeFuncCache) decodeFunc {
	,  := .Key(), .Elem()
	 := reflect.Zero()
	 := reflect.Zero()
	 := TypeOf()
	 := decodeFuncOf(, )

	return func( Reader,  reflect.Value,  flags) error {
		,  := .ReadSet()
		if  != nil {
			return 
		}

		// See decodeFuncSliceOf for details about why this type conversion
		// needs to be done.
		switch .Type {
		case TRUE:
			.Type = BOOL
		}

		.Set(reflect.MakeMapWithSize(, int(.Size)))

		if .Size == 0 {
			return nil
		}

		// TODO: implement type conversions?
		if  != .Type {
			if .have(strict) {
				return &TypeMismatch{item: "list item", Expect: , Found: .Type}
			}
			return nil
		}

		 := reflect.New().Elem()
		 = .only(decodeFlags)

		for  := 0;  < int(.Size); ++ {
			if  := (, , );  != nil {
				return with(dontExpectEOF(), &decodeErrorSet{cause: , index: })
			}
			.SetMapIndex(, )
			.Set()
		}

		return nil
	}
}

type structDecoder struct {
	fields   []structDecoderField
	union    []int
	minID    int16
	zero     reflect.Value
	required []uint64
}

func ( *structDecoder) ( Reader,  reflect.Value,  flags) error {
	 = .only(decodeFlags)
	 := .have(coalesceBoolFields)

	 := reflect.Value{}
	 := len(.union) > 0
	 := make([]uint64, 1)
	if len(.required) > len() {
		 = make([]uint64, len(.required))
	}

	 := readStruct(, func( Reader,  Field) error {
		 := int(.ID) - int(.minID)
		if  < 0 ||  >= len(.fields) || .fields[].decode == nil {
			return skipField(, )
		}
		 := &.fields[]
		[/64] |= 1 << ( % 64)

		// TODO: implement type conversions?
		if .Type != .typ && !(.Type == TRUE && .typ == BOOL) {
			if .have(strict) {
				return &TypeMismatch{item: "field value", Expect: .typ, Found: .Type}
			}
			return nil
		}

		 := 
		for ,  := range .index {
			if .Kind() == reflect.Ptr {
				 = .Elem()
			}
			if  = .Field(); .Kind() == reflect.Ptr {
				if .IsNil() {
					.Set(reflect.New(.Type().Elem()))
				}
			}
		}

		if  {
			.Set(.zero)
		}

		 = 

		if  && (.Type == TRUE || .Type == FALSE) {
			for .Kind() == reflect.Ptr {
				if .IsNil() {
					.Set(reflect.New(.Type().Elem()))
				}
				 = .Elem()
			}
			.SetBool(.Type == TRUE)
			return nil
		}

		return .decode(, , .with(.flags))
	})
	if  != nil {
		return 
	}

	for ,  := range .required {
		if  :=  & [];  !=  {
			 *= 64
			for ( & 1) != 0 {
				 >>= 1
				++
			}
			 := &.fields[]
			return &MissingField{Field: Field{ID: .id, Type: .typ}}
		}
	}

	if  && .IsValid() {
		.FieldByIndex(.union).Set(.Addr())
	}

	return nil
}

type structDecoderField struct {
	index  []int
	id     int16
	flags  flags
	typ    Type
	decode decodeFunc
}

func decodeFuncStructOf( reflect.Type,  decodeFuncCache) decodeFunc {
	 := &structDecoder{
		zero: reflect.Zero(),
	}
	 := .decode
	[] = 

	 := make([]structDecoderField, 0, .NumField())
	forEachStructField(, nil, func( structField) {
		if .flags.have(union) {
			.union = .index
		} else {
			 = append(, structDecoderField{
				index:  .index,
				id:     .id,
				flags:  .flags,
				typ:    TypeOf(.typ),
				decode: decodeFuncStructFieldOf(, ),
			})
		}
	})

	 := int16(0)
	 := int16(0)

	for ,  := range  {
		if .id <  ||  == 0 {
			 = .id
		}
		if .id >  {
			 = .id
		}
	}

	.fields = make([]structDecoderField, (-)+1)
	.minID = 
	.required = make([]uint64, len()/64+1)

	for ,  := range  {
		 := .id - 
		 := .fields[]
		if .decode != nil {
			panic(fmt.Errorf("thrift struct field id %d is present multiple times in %s with types %s and %s", .id, , .typ, .typ))
		}
		.fields[] = 
		if .flags.have(required) {
			.required[/64] |= 1 << ( % 64)
		}
	}

	return 
}

func decodeFuncStructFieldOf( structField,  decodeFuncCache) decodeFunc {
	if .flags.have(enum) {
		switch .typ.Kind() {
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			return decodeInt32
		}
	}
	return decodeFuncOf(.typ, )
}

func decodeFuncPtrOf( reflect.Type,  decodeFuncCache) decodeFunc {
	 := .Elem()
	 := decodeFuncOf(.Elem(), )
	return func( Reader,  reflect.Value,  flags) error {
		if .IsNil() {
			.Set(reflect.New())
		}
		return (, .Elem(), )
	}
}

func readBinary( Reader,  func(io.Reader) error) error {
	,  := .ReadLength()
	if  != nil {
		return 
	}
	return dontExpectEOF((io.LimitReader(.Reader(), int64())))
}

func readList( Reader,  func(Reader, Type) error) error {
	,  := .ReadList()
	if  != nil {
		return 
	}

	for  := 0;  < int(.Size); ++ {
		if  := (, .Type);  != nil {
			return with(dontExpectEOF(), &decodeErrorList{cause: , index: })
		}
	}

	return nil
}

func readSet( Reader,  func(Reader, Type) error) error {
	,  := .ReadSet()
	if  != nil {
		return 
	}

	for  := 0;  < int(.Size); ++ {
		if  := (, .Type);  != nil {
			return with(dontExpectEOF(), &decodeErrorSet{cause: , index: })
		}
	}

	return nil
}

func readMap( Reader,  func(Reader, Type, Type) error) error {
	,  := .ReadMap()
	if  != nil {
		return 
	}

	for  := 0;  < int(.Size); ++ {
		if  := (, .Key, .Value);  != nil {
			return with(dontExpectEOF(), &decodeErrorMap{cause: , index: })
		}
	}

	return nil
}

func readStruct( Reader,  func(Reader, Field) error) error {
	 := int16(0)
	 := 0

	for {
		,  := .ReadField()
		if  != nil {
			if  > 0 {
				 = dontExpectEOF()
			}
			return 
		}

		if .Type == STOP {
			return nil
		}

		if .Delta {
			.ID += 
			.Delta = false
		}

		if  := (, );  != nil {
			return with(dontExpectEOF(), &decodeErrorField{cause: })
		}

		 = .ID
		++
	}
}

func skip( Reader,  Type) error {
	var  error
	switch  {
	case TRUE, FALSE:
		_,  = .ReadBool()
	case I8:
		_,  = .ReadInt8()
	case I16:
		_,  = .ReadInt16()
	case I32:
		_,  = .ReadInt32()
	case I64:
		_,  = .ReadInt64()
	case DOUBLE:
		_,  = .ReadFloat64()
	case BINARY:
		 = skipBinary()
	case LIST:
		 = skipList()
	case SET:
		 = skipSet()
	case MAP:
		 = skipMap()
	case STRUCT:
		 = skipStruct()
	default:
		return fmt.Errorf("skipping unsupported thrift type %d", )
	}
	return 
}

func skipBinary( Reader) error {
	,  := .ReadLength()
	if  != nil {
		return 
	}
	if  == 0 {
		return nil
	}
	switch x := .Reader().(type) {
	case *bufio.Reader:
		_,  = .Discard(int())
	default:
		_,  = io.CopyN(io.Discard, , int64())
	}
	return dontExpectEOF()
}

func skipList( Reader) error {
	return readList(, skip)
}

func skipSet( Reader) error {
	return readSet(, skip)
}

func skipMap( Reader) error {
	return readMap(, func( Reader, ,  Type) error {
		if  := skip(, );  != nil {
			return dontExpectEOF()
		}
		if  := skip(, );  != nil {
			return dontExpectEOF()
		}
		return nil
	})
}

func skipStruct( Reader) error {
	return readStruct(, skipField)
}

func skipField( Reader,  Field) error {
	return skip(, .Type)
}