// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

//go:generate go run encgen.go -output enc_helpers.go

package gob

import (
	
	
	
	
	
	
)

const uint64Size = 8

type encHelper func(state *encoderState, v reflect.Value) bool

// encoderState is the global execution state of an instance of the encoder.
// Field numbers are delta encoded and always increase. The field
// number is initialized to -1 so 0 comes out as delta(1). A delta of
// 0 terminates the structure.
type encoderState struct {
	enc      *Encoder
	b        *encBuffer
	sendZero bool                 // encoding an array element or map key/value pair; send zero values
	fieldnum int                  // the last field number written.
	buf      [1 + uint64Size]byte // buffer used by the encoder; here to avoid allocation.
	next     *encoderState        // for free list
}

// encBuffer is an extremely simple, fast implementation of a write-only byte buffer.
// It never returns a non-nil error, but Write returns an error value so it matches io.Writer.
type encBuffer struct {
	data    []byte
	scratch [64]byte
}

var encBufferPool = sync.Pool{
	New: func() interface{} {
		 := new(encBuffer)
		.data = .scratch[0:0]
		return 
	},
}

func ( *encBuffer) ( byte) {
	.data = append(.data, )
}

func ( *encBuffer) ( []byte) (int, error) {
	.data = append(.data, ...)
	return len(), nil
}

func ( *encBuffer) ( string) {
	.data = append(.data, ...)
}

func ( *encBuffer) () int {
	return len(.data)
}

func ( *encBuffer) () []byte {
	return .data
}

func ( *encBuffer) () {
	if len(.data) >= tooBig {
		.data = .scratch[0:0]
	} else {
		.data = .data[0:0]
	}
}

func ( *Encoder) ( *encBuffer) *encoderState {
	 := .freeList
	if  == nil {
		 = new(encoderState)
		.enc = 
	} else {
		.freeList = .next
	}
	.sendZero = false
	.fieldnum = 0
	.b = 
	if len(.data) == 0 {
		.data = .scratch[0:0]
	}
	return 
}

func ( *Encoder) ( *encoderState) {
	.next = .freeList
	.freeList = 
}

// Unsigned integers have a two-state encoding. If the number is less
// than 128 (0 through 0x7F), its value is written directly.
// Otherwise the value is written in big-endian byte order preceded
// by the byte length, negated.

// encodeUint writes an encoded unsigned integer to state.b.
func ( *encoderState) ( uint64) {
	if  <= 0x7F {
		.b.writeByte(uint8())
		return
	}

	binary.BigEndian.PutUint64(.buf[1:], )
	 := bits.LeadingZeros64() >> 3      // 8 - bytelen(x)
	.buf[] = uint8( - uint64Size) // and then we subtract 8 to get -bytelen(x)

	.b.Write(.buf[ : uint64Size+1])
}

// encodeInt writes an encoded signed integer to state.w.
// The low bit of the encoding says whether to bit complement the (other bits of the)
// uint to recover the int.
func ( *encoderState) ( int64) {
	var  uint64
	if  < 0 {
		 = uint64(^<<1) | 1
	} else {
		 = uint64( << 1)
	}
	.encodeUint()
}

// encOp is the signature of an encoding operator for a given type.
type encOp func(i *encInstr, state *encoderState, v reflect.Value)

// The 'instructions' of the encoding machine
type encInstr struct {
	op    encOp
	field int   // field number in input
	index []int // struct index
	indir int   // how many pointer indirections to reach the value in the struct
}

// update emits a field number and updates the state to record its value for delta encoding.
// If the instruction pointer is nil, it does nothing
func ( *encoderState) ( *encInstr) {
	if  != nil {
		.encodeUint(uint64(.field - .fieldnum))
		.fieldnum = .field
	}
}

// Each encoder for a composite is responsible for handling any
// indirections associated with the elements of the data structure.
// If any pointer so reached is nil, no bytes are written. If the
// data item is zero, no bytes are written. Single values - ints,
// strings etc. - are indirected before calling their encoders.
// Otherwise, the output (for a scalar) is the field number, as an
// encoded integer, followed by the field data in its appropriate
// format.

// encIndirect dereferences pv indir times and returns the result.
func encIndirect( reflect.Value,  int) reflect.Value {
	for ;  > 0; -- {
		if .IsNil() {
			break
		}
		 = .Elem()
	}
	return 
}

// encBool encodes the bool referenced by v as an unsigned 0 or 1.
func encBool( *encInstr,  *encoderState,  reflect.Value) {
	 := .Bool()
	if  || .sendZero {
		.update()
		if  {
			.encodeUint(1)
		} else {
			.encodeUint(0)
		}
	}
}

// encInt encodes the signed integer (int int8 int16 int32 int64) referenced by v.
func encInt( *encInstr,  *encoderState,  reflect.Value) {
	 := .Int()
	if  != 0 || .sendZero {
		.update()
		.encodeInt()
	}
}

// encUint encodes the unsigned integer (uint uint8 uint16 uint32 uint64 uintptr) referenced by v.
func encUint( *encInstr,  *encoderState,  reflect.Value) {
	 := .Uint()
	if  != 0 || .sendZero {
		.update()
		.encodeUint()
	}
}

// floatBits returns a uint64 holding the bits of a floating-point number.
// Floating-point numbers are transmitted as uint64s holding the bits
// of the underlying representation. They are sent byte-reversed, with
// the exponent end coming out first, so integer floating point numbers
// (for example) transmit more compactly. This routine does the
// swizzling.
func floatBits( float64) uint64 {
	 := math.Float64bits()
	return bits.ReverseBytes64()
}

// encFloat encodes the floating point value (float32 float64) referenced by v.
func encFloat( *encInstr,  *encoderState,  reflect.Value) {
	 := .Float()
	if  != 0 || .sendZero {
		 := floatBits()
		.update()
		.encodeUint()
	}
}

// encComplex encodes the complex value (complex64 complex128) referenced by v.
// Complex numbers are just a pair of floating-point numbers, real part first.
func encComplex( *encInstr,  *encoderState,  reflect.Value) {
	 := .Complex()
	if  != 0+0i || .sendZero {
		 := floatBits(real())
		 := floatBits(imag())
		.update()
		.encodeUint()
		.encodeUint()
	}
}

// encUint8Array encodes the byte array referenced by v.
// Byte arrays are encoded as an unsigned count followed by the raw bytes.
func encUint8Array( *encInstr,  *encoderState,  reflect.Value) {
	 := .Bytes()
	if len() > 0 || .sendZero {
		.update()
		.encodeUint(uint64(len()))
		.b.Write()
	}
}

// encString encodes the string referenced by v.
// Strings are encoded as an unsigned count followed by the raw bytes.
func encString( *encInstr,  *encoderState,  reflect.Value) {
	 := .String()
	if len() > 0 || .sendZero {
		.update()
		.encodeUint(uint64(len()))
		.b.WriteString()
	}
}

// encStructTerminator encodes the end of an encoded struct
// as delta field number of 0.
func encStructTerminator( *encInstr,  *encoderState,  reflect.Value) {
	.encodeUint(0)
}

// Execution engine

// encEngine an array of instructions indexed by field number of the encoding
// data, typically a struct. It is executed top to bottom, walking the struct.
type encEngine struct {
	instr []encInstr
}

const singletonField = 0

// valid reports whether the value is valid and a non-nil pointer.
// (Slices, maps, and chans take care of themselves.)
func valid( reflect.Value) bool {
	switch .Kind() {
	case reflect.Invalid:
		return false
	case reflect.Ptr:
		return !.IsNil()
	}
	return true
}

// encodeSingle encodes a single top-level non-struct value.
func ( *Encoder) ( *encBuffer,  *encEngine,  reflect.Value) {
	 := .newEncoderState()
	defer .freeEncoderState()
	.fieldnum = singletonField
	// There is no surrounding struct to frame the transmission, so we must
	// generate data even if the item is zero. To do this, set sendZero.
	.sendZero = true
	 := &.instr[singletonField]
	if .indir > 0 {
		 = encIndirect(, .indir)
	}
	if valid() {
		.op(, , )
	}
}

// encodeStruct encodes a single struct value.
func ( *Encoder) ( *encBuffer,  *encEngine,  reflect.Value) {
	if !valid() {
		return
	}
	 := .newEncoderState()
	defer .freeEncoderState()
	.fieldnum = -1
	for  := 0;  < len(.instr); ++ {
		 := &.instr[]
		if  >= .NumField() {
			// encStructTerminator
			.op(, , reflect.Value{})
			break
		}
		 := .FieldByIndex(.index)
		if .indir > 0 {
			 = encIndirect(, .indir)
			// TODO: Is field guaranteed valid? If so we could avoid this check.
			if !valid() {
				continue
			}
		}
		.op(, , )
	}
}

// encodeArray encodes an array.
func ( *Encoder) ( *encBuffer,  reflect.Value,  encOp,  int,  int,  encHelper) {
	 := .newEncoderState()
	defer .freeEncoderState()
	.fieldnum = -1
	.sendZero = true
	.encodeUint(uint64())
	if  != nil && (, ) {
		return
	}
	for  := 0;  < ; ++ {
		 := .Index()
		if  > 0 {
			 = encIndirect(, )
			// TODO: Is elem guaranteed valid? If so we could avoid this check.
			if !valid() {
				errorf("encodeArray: nil element")
			}
		}
		(nil, , )
	}
}

// encodeReflectValue is a helper for maps. It encodes the value v.
func encodeReflectValue( *encoderState,  reflect.Value,  encOp,  int) {
	for  := 0;  <  && .IsValid(); ++ {
		 = reflect.Indirect()
	}
	if !.IsValid() {
		errorf("encodeReflectValue: nil element")
	}
	(nil, , )
}

// encodeMap encodes a map as unsigned count followed by key:value pairs.
func ( *Encoder) ( *encBuffer,  reflect.Value, ,  encOp, ,  int) {
	 := .newEncoderState()
	.fieldnum = -1
	.sendZero = true
	 := .MapKeys()
	.encodeUint(uint64(len()))
	for ,  := range  {
		encodeReflectValue(, , , )
		encodeReflectValue(, .MapIndex(), , )
	}
	.freeEncoderState()
}

// encodeInterface encodes the interface value iv.
// To send an interface, we send a string identifying the concrete type, followed
// by the type identifier (which might require defining that type right now), followed
// by the concrete value. A nil value gets sent as the empty string for the name,
// followed by no value.
func ( *Encoder) ( *encBuffer,  reflect.Value) {
	// Gobs can encode nil interface values but not typed interface
	// values holding nil pointers, since nil pointers point to no value.
	 := .Elem()
	if .Kind() == reflect.Ptr && .IsNil() {
		errorf("gob: cannot encode nil pointer of type %s inside interface", .Elem().Type())
	}
	 := .newEncoderState()
	.fieldnum = -1
	.sendZero = true
	if .IsNil() {
		.encodeUint(0)
		return
	}

	 := userType(.Elem().Type())
	,  := concreteTypeToName.Load(.base)
	if ! {
		errorf("type not registered for interface: %s", .base)
	}
	 := .(string)

	// Send the name.
	.encodeUint(uint64(len()))
	.b.WriteString()
	// Define the type id if necessary.
	.sendTypeDescriptor(.writer(), , )
	// Send the type id.
	.sendTypeId(, )
	// Encode the value into a new buffer. Any nested type definitions
	// should be written to b, before the encoded value.
	.pushWriter()
	 := encBufferPool.Get().(*encBuffer)
	.Write(spaceForLength)
	.encode(, , )
	if .err != nil {
		error_(.err)
	}
	.popWriter()
	.writeMessage(, )
	.Reset()
	encBufferPool.Put()
	if .err != nil {
		error_(.err)
	}
	.freeEncoderState()
}

// isZero reports whether the value is the zero of its type.
func isZero( reflect.Value) bool {
	switch .Kind() {
	case reflect.Array:
		for  := 0;  < .Len(); ++ {
			if !(.Index()) {
				return false
			}
		}
		return true
	case reflect.Map, reflect.Slice, reflect.String:
		return .Len() == 0
	case reflect.Bool:
		return !.Bool()
	case reflect.Complex64, reflect.Complex128:
		return .Complex() == 0
	case reflect.Chan, reflect.Func, reflect.Interface, reflect.Ptr:
		return .IsNil()
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return .Int() == 0
	case reflect.Float32, reflect.Float64:
		return .Float() == 0
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		return .Uint() == 0
	case reflect.Struct:
		for  := 0;  < .NumField(); ++ {
			if !(.Field()) {
				return false
			}
		}
		return true
	}
	panic("unknown type in isZero " + .Type().String())
}

// encGobEncoder encodes a value that implements the GobEncoder interface.
// The data is sent as a byte array.
func ( *Encoder) ( *encBuffer,  *userTypeInfo,  reflect.Value) {
	// TODO: should we catch panics from the called method?

	var  []byte
	var  error
	// We know it's one of these.
	switch .externalEnc {
	case xGob:
		,  = .Interface().(GobEncoder).GobEncode()
	case xBinary:
		,  = .Interface().(encoding.BinaryMarshaler).MarshalBinary()
	case xText:
		,  = .Interface().(encoding.TextMarshaler).MarshalText()
	}
	if  != nil {
		error_()
	}
	 := .newEncoderState()
	.fieldnum = -1
	.encodeUint(uint64(len()))
	.b.Write()
	.freeEncoderState()
}

var encOpTable = [...]encOp{
	reflect.Bool:       encBool,
	reflect.Int:        encInt,
	reflect.Int8:       encInt,
	reflect.Int16:      encInt,
	reflect.Int32:      encInt,
	reflect.Int64:      encInt,
	reflect.Uint:       encUint,
	reflect.Uint8:      encUint,
	reflect.Uint16:     encUint,
	reflect.Uint32:     encUint,
	reflect.Uint64:     encUint,
	reflect.Uintptr:    encUint,
	reflect.Float32:    encFloat,
	reflect.Float64:    encFloat,
	reflect.Complex64:  encComplex,
	reflect.Complex128: encComplex,
	reflect.String:     encString,
}

// encOpFor returns (a pointer to) the encoding op for the base type under rt and
// the indirection count to reach it.
func encOpFor( reflect.Type,  map[reflect.Type]*encOp,  map[*typeInfo]bool) (*encOp, int) {
	 := userType()
	// If the type implements GobEncoder, we handle it without further processing.
	if .externalEnc != 0 {
		return gobEncodeOpFor()
	}
	// If this type is already in progress, it's a recursive type (e.g. map[string]*T).
	// Return the pointer to the op we're already building.
	if  := [];  != nil {
		return , .indir
	}
	 := .base
	 := .indir
	 := .Kind()
	var  encOp
	if int() < len(encOpTable) {
		 = encOpTable[]
	}
	if  == nil {
		[] = &
		// Special cases
		switch  := ; .Kind() {
		case reflect.Slice:
			if .Elem().Kind() == reflect.Uint8 {
				 = encUint8Array
				break
			}
			// Slices have a header; we decode it to find the underlying array.
			,  := (.Elem(), , )
			 := encSliceHelper[.Elem().Kind()]
			 = func( *encInstr,  *encoderState,  reflect.Value) {
				if !.sendZero && .Len() == 0 {
					return
				}
				.update()
				.enc.encodeArray(.b, , *, , .Len(), )
			}
		case reflect.Array:
			// True arrays have size in the type.
			,  := (.Elem(), , )
			 := encArrayHelper[.Elem().Kind()]
			 = func( *encInstr,  *encoderState,  reflect.Value) {
				.update()
				.enc.encodeArray(.b, , *, , .Len(), )
			}
		case reflect.Map:
			,  := (.Key(), , )
			,  := (.Elem(), , )
			 = func( *encInstr,  *encoderState,  reflect.Value) {
				// We send zero-length (but non-nil) maps because the
				// receiver might want to use the map.  (Maps don't use append.)
				if !.sendZero && .IsNil() {
					return
				}
				.update()
				.enc.encodeMap(.b, , *, *, , )
			}
		case reflect.Struct:
			// Generate a closure that calls out to the engine for the nested type.
			getEncEngine(userType(), )
			 := mustGetTypeInfo()
			 = func( *encInstr,  *encoderState,  reflect.Value) {
				.update()
				// indirect through info to delay evaluation for recursive structs
				 := .encoder.Load().(*encEngine)
				.enc.encodeStruct(.b, , )
			}
		case reflect.Interface:
			 = func( *encInstr,  *encoderState,  reflect.Value) {
				if !.sendZero && (!.IsValid() || .IsNil()) {
					return
				}
				.update()
				.enc.encodeInterface(.b, )
			}
		}
	}
	if  == nil {
		errorf("can't happen: encode type %s", )
	}
	return &, 
}

// gobEncodeOpFor returns the op for a type that is known to implement GobEncoder.
func gobEncodeOpFor( *userTypeInfo) (*encOp, int) {
	 := .user
	if .encIndir == -1 {
		 = reflect.PtrTo()
	} else if .encIndir > 0 {
		for  := int8(0);  < .encIndir; ++ {
			 = .Elem()
		}
	}
	var  encOp
	 = func( *encInstr,  *encoderState,  reflect.Value) {
		if .encIndir == -1 {
			// Need to climb up one level to turn value into pointer.
			if !.CanAddr() {
				errorf("unaddressable value of type %s", )
			}
			 = .Addr()
		}
		if !.sendZero && isZero() {
			return
		}
		.update()
		.enc.encodeGobEncoder(.b, , )
	}
	return &, int(.encIndir) // encIndir: op will get called with p == address of receiver.
}

// compileEnc returns the engine to compile the type.
func compileEnc( *userTypeInfo,  map[*typeInfo]bool) *encEngine {
	 := .base
	 := new(encEngine)
	 := make(map[reflect.Type]*encOp)
	 := .base
	if .externalEnc != 0 {
		 = .user
	}
	if .externalEnc == 0 && .Kind() == reflect.Struct {
		for ,  := 0, 0;  < .NumField(); ++ {
			 := .Field()
			if !isSent(&) {
				continue
			}
			,  := encOpFor(.Type, , )
			.instr = append(.instr, encInstr{*, , .Index, })
			++
		}
		if .NumField() > 0 && len(.instr) == 0 {
			errorf("type %s has no exported fields", )
		}
		.instr = append(.instr, encInstr{encStructTerminator, 0, nil, 0})
	} else {
		.instr = make([]encInstr, 1)
		,  := encOpFor(, , )
		.instr[0] = encInstr{*, singletonField, nil, }
	}
	return 
}

// getEncEngine returns the engine to compile the type.
func getEncEngine( *userTypeInfo,  map[*typeInfo]bool) *encEngine {
	,  := getTypeInfo()
	if  != nil {
		error_()
	}
	,  := .encoder.Load().(*encEngine)
	if ! {
		 = buildEncEngine(, , )
	}
	return 
}

func buildEncEngine( *typeInfo,  *userTypeInfo,  map[*typeInfo]bool) *encEngine {
	// Check for recursive types.
	if  != nil && [] {
		return nil
	}
	.encInit.Lock()
	defer .encInit.Unlock()
	,  := .encoder.Load().(*encEngine)
	if ! {
		if  == nil {
			 = make(map[*typeInfo]bool)
		}
		[] = true
		 = compileEnc(, )
		.encoder.Store()
	}
	return 
}

func ( *Encoder) ( *encBuffer,  reflect.Value,  *userTypeInfo) {
	defer catchError(&.err)
	 := getEncEngine(, nil)
	 := .indir
	if .externalEnc != 0 {
		 = int(.encIndir)
	}
	for  := 0;  < ; ++ {
		 = reflect.Indirect()
	}
	if .externalEnc == 0 && .Type().Kind() == reflect.Struct {
		.encodeStruct(, , )
	} else {
		.encodeSingle(, , )
	}
}