github.com/rohankumardubey/syslog-redirector-golang@v0.0.0-20140320174030-4859f03d829a/src/pkg/encoding/gob/encode.go (about)

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package gob
     6  
     7  import (
     8  	"bytes"
     9  	"encoding"
    10  	"math"
    11  	"reflect"
    12  	"unsafe"
    13  )
    14  
    15  const uint64Size = int(unsafe.Sizeof(uint64(0)))
    16  
    17  // encoderState is the global execution state of an instance of the encoder.
    18  // Field numbers are delta encoded and always increase. The field
    19  // number is initialized to -1 so 0 comes out as delta(1). A delta of
    20  // 0 terminates the structure.
    21  type encoderState struct {
    22  	enc      *Encoder
    23  	b        *bytes.Buffer
    24  	sendZero bool                 // encoding an array element or map key/value pair; send zero values
    25  	fieldnum int                  // the last field number written.
    26  	buf      [1 + uint64Size]byte // buffer used by the encoder; here to avoid allocation.
    27  	next     *encoderState        // for free list
    28  }
    29  
    30  func (enc *Encoder) newEncoderState(b *bytes.Buffer) *encoderState {
    31  	e := enc.freeList
    32  	if e == nil {
    33  		e = new(encoderState)
    34  		e.enc = enc
    35  	} else {
    36  		enc.freeList = e.next
    37  	}
    38  	e.sendZero = false
    39  	e.fieldnum = 0
    40  	e.b = b
    41  	return e
    42  }
    43  
    44  func (enc *Encoder) freeEncoderState(e *encoderState) {
    45  	e.next = enc.freeList
    46  	enc.freeList = e
    47  }
    48  
    49  // Unsigned integers have a two-state encoding.  If the number is less
    50  // than 128 (0 through 0x7F), its value is written directly.
    51  // Otherwise the value is written in big-endian byte order preceded
    52  // by the byte length, negated.
    53  
    54  // encodeUint writes an encoded unsigned integer to state.b.
    55  func (state *encoderState) encodeUint(x uint64) {
    56  	if x <= 0x7F {
    57  		err := state.b.WriteByte(uint8(x))
    58  		if err != nil {
    59  			error_(err)
    60  		}
    61  		return
    62  	}
    63  	i := uint64Size
    64  	for x > 0 {
    65  		state.buf[i] = uint8(x)
    66  		x >>= 8
    67  		i--
    68  	}
    69  	state.buf[i] = uint8(i - uint64Size) // = loop count, negated
    70  	_, err := state.b.Write(state.buf[i : uint64Size+1])
    71  	if err != nil {
    72  		error_(err)
    73  	}
    74  }
    75  
    76  // encodeInt writes an encoded signed integer to state.w.
    77  // The low bit of the encoding says whether to bit complement the (other bits of the)
    78  // uint to recover the int.
    79  func (state *encoderState) encodeInt(i int64) {
    80  	var x uint64
    81  	if i < 0 {
    82  		x = uint64(^i<<1) | 1
    83  	} else {
    84  		x = uint64(i << 1)
    85  	}
    86  	state.encodeUint(uint64(x))
    87  }
    88  
    89  // encOp is the signature of an encoding operator for a given type.
    90  type encOp func(i *encInstr, state *encoderState, p unsafe.Pointer)
    91  
    92  // The 'instructions' of the encoding machine
    93  type encInstr struct {
    94  	op     encOp
    95  	field  int     // field number
    96  	indir  int     // how many pointer indirections to reach the value in the struct
    97  	offset uintptr // offset in the structure of the field to encode
    98  }
    99  
   100  // update emits a field number and updates the state to record its value for delta encoding.
   101  // If the instruction pointer is nil, it does nothing
   102  func (state *encoderState) update(instr *encInstr) {
   103  	if instr != nil {
   104  		state.encodeUint(uint64(instr.field - state.fieldnum))
   105  		state.fieldnum = instr.field
   106  	}
   107  }
   108  
   109  // Each encoder for a composite is responsible for handling any
   110  // indirections associated with the elements of the data structure.
   111  // If any pointer so reached is nil, no bytes are written.  If the
   112  // data item is zero, no bytes are written.  Single values - ints,
   113  // strings etc. - are indirected before calling their encoders.
   114  // Otherwise, the output (for a scalar) is the field number, as an
   115  // encoded integer, followed by the field data in its appropriate
   116  // format.
   117  
   118  // encIndirect dereferences p indir times and returns the result.
   119  func encIndirect(p unsafe.Pointer, indir int) unsafe.Pointer {
   120  	for ; indir > 0; indir-- {
   121  		p = *(*unsafe.Pointer)(p)
   122  		if p == nil {
   123  			return unsafe.Pointer(nil)
   124  		}
   125  	}
   126  	return p
   127  }
   128  
   129  // encBool encodes the bool with address p as an unsigned 0 or 1.
   130  func encBool(i *encInstr, state *encoderState, p unsafe.Pointer) {
   131  	b := *(*bool)(p)
   132  	if b || state.sendZero {
   133  		state.update(i)
   134  		if b {
   135  			state.encodeUint(1)
   136  		} else {
   137  			state.encodeUint(0)
   138  		}
   139  	}
   140  }
   141  
   142  // encInt encodes the int with address p.
   143  func encInt(i *encInstr, state *encoderState, p unsafe.Pointer) {
   144  	v := int64(*(*int)(p))
   145  	if v != 0 || state.sendZero {
   146  		state.update(i)
   147  		state.encodeInt(v)
   148  	}
   149  }
   150  
   151  // encUint encodes the uint with address p.
   152  func encUint(i *encInstr, state *encoderState, p unsafe.Pointer) {
   153  	v := uint64(*(*uint)(p))
   154  	if v != 0 || state.sendZero {
   155  		state.update(i)
   156  		state.encodeUint(v)
   157  	}
   158  }
   159  
   160  // encInt8 encodes the int8 with address p.
   161  func encInt8(i *encInstr, state *encoderState, p unsafe.Pointer) {
   162  	v := int64(*(*int8)(p))
   163  	if v != 0 || state.sendZero {
   164  		state.update(i)
   165  		state.encodeInt(v)
   166  	}
   167  }
   168  
   169  // encUint8 encodes the uint8 with address p.
   170  func encUint8(i *encInstr, state *encoderState, p unsafe.Pointer) {
   171  	v := uint64(*(*uint8)(p))
   172  	if v != 0 || state.sendZero {
   173  		state.update(i)
   174  		state.encodeUint(v)
   175  	}
   176  }
   177  
   178  // encInt16 encodes the int16 with address p.
   179  func encInt16(i *encInstr, state *encoderState, p unsafe.Pointer) {
   180  	v := int64(*(*int16)(p))
   181  	if v != 0 || state.sendZero {
   182  		state.update(i)
   183  		state.encodeInt(v)
   184  	}
   185  }
   186  
   187  // encUint16 encodes the uint16 with address p.
   188  func encUint16(i *encInstr, state *encoderState, p unsafe.Pointer) {
   189  	v := uint64(*(*uint16)(p))
   190  	if v != 0 || state.sendZero {
   191  		state.update(i)
   192  		state.encodeUint(v)
   193  	}
   194  }
   195  
   196  // encInt32 encodes the int32 with address p.
   197  func encInt32(i *encInstr, state *encoderState, p unsafe.Pointer) {
   198  	v := int64(*(*int32)(p))
   199  	if v != 0 || state.sendZero {
   200  		state.update(i)
   201  		state.encodeInt(v)
   202  	}
   203  }
   204  
   205  // encUint encodes the uint32 with address p.
   206  func encUint32(i *encInstr, state *encoderState, p unsafe.Pointer) {
   207  	v := uint64(*(*uint32)(p))
   208  	if v != 0 || state.sendZero {
   209  		state.update(i)
   210  		state.encodeUint(v)
   211  	}
   212  }
   213  
   214  // encInt64 encodes the int64 with address p.
   215  func encInt64(i *encInstr, state *encoderState, p unsafe.Pointer) {
   216  	v := *(*int64)(p)
   217  	if v != 0 || state.sendZero {
   218  		state.update(i)
   219  		state.encodeInt(v)
   220  	}
   221  }
   222  
   223  // encInt64 encodes the uint64 with address p.
   224  func encUint64(i *encInstr, state *encoderState, p unsafe.Pointer) {
   225  	v := *(*uint64)(p)
   226  	if v != 0 || state.sendZero {
   227  		state.update(i)
   228  		state.encodeUint(v)
   229  	}
   230  }
   231  
   232  // encUintptr encodes the uintptr with address p.
   233  func encUintptr(i *encInstr, state *encoderState, p unsafe.Pointer) {
   234  	v := uint64(*(*uintptr)(p))
   235  	if v != 0 || state.sendZero {
   236  		state.update(i)
   237  		state.encodeUint(v)
   238  	}
   239  }
   240  
   241  // floatBits returns a uint64 holding the bits of a floating-point number.
   242  // Floating-point numbers are transmitted as uint64s holding the bits
   243  // of the underlying representation.  They are sent byte-reversed, with
   244  // the exponent end coming out first, so integer floating point numbers
   245  // (for example) transmit more compactly.  This routine does the
   246  // swizzling.
   247  func floatBits(f float64) uint64 {
   248  	u := math.Float64bits(f)
   249  	var v uint64
   250  	for i := 0; i < 8; i++ {
   251  		v <<= 8
   252  		v |= u & 0xFF
   253  		u >>= 8
   254  	}
   255  	return v
   256  }
   257  
   258  // encFloat32 encodes the float32 with address p.
   259  func encFloat32(i *encInstr, state *encoderState, p unsafe.Pointer) {
   260  	f := *(*float32)(p)
   261  	if f != 0 || state.sendZero {
   262  		v := floatBits(float64(f))
   263  		state.update(i)
   264  		state.encodeUint(v)
   265  	}
   266  }
   267  
   268  // encFloat64 encodes the float64 with address p.
   269  func encFloat64(i *encInstr, state *encoderState, p unsafe.Pointer) {
   270  	f := *(*float64)(p)
   271  	if f != 0 || state.sendZero {
   272  		state.update(i)
   273  		v := floatBits(f)
   274  		state.encodeUint(v)
   275  	}
   276  }
   277  
   278  // encComplex64 encodes the complex64 with address p.
   279  // Complex numbers are just a pair of floating-point numbers, real part first.
   280  func encComplex64(i *encInstr, state *encoderState, p unsafe.Pointer) {
   281  	c := *(*complex64)(p)
   282  	if c != 0+0i || state.sendZero {
   283  		rpart := floatBits(float64(real(c)))
   284  		ipart := floatBits(float64(imag(c)))
   285  		state.update(i)
   286  		state.encodeUint(rpart)
   287  		state.encodeUint(ipart)
   288  	}
   289  }
   290  
   291  // encComplex128 encodes the complex128 with address p.
   292  func encComplex128(i *encInstr, state *encoderState, p unsafe.Pointer) {
   293  	c := *(*complex128)(p)
   294  	if c != 0+0i || state.sendZero {
   295  		rpart := floatBits(real(c))
   296  		ipart := floatBits(imag(c))
   297  		state.update(i)
   298  		state.encodeUint(rpart)
   299  		state.encodeUint(ipart)
   300  	}
   301  }
   302  
   303  // encUint8Array encodes the byte slice whose header has address p.
   304  // Byte arrays are encoded as an unsigned count followed by the raw bytes.
   305  func encUint8Array(i *encInstr, state *encoderState, p unsafe.Pointer) {
   306  	b := *(*[]byte)(p)
   307  	if len(b) > 0 || state.sendZero {
   308  		state.update(i)
   309  		state.encodeUint(uint64(len(b)))
   310  		state.b.Write(b)
   311  	}
   312  }
   313  
   314  // encString encodes the string whose header has address p.
   315  // Strings are encoded as an unsigned count followed by the raw bytes.
   316  func encString(i *encInstr, state *encoderState, p unsafe.Pointer) {
   317  	s := *(*string)(p)
   318  	if len(s) > 0 || state.sendZero {
   319  		state.update(i)
   320  		state.encodeUint(uint64(len(s)))
   321  		state.b.WriteString(s)
   322  	}
   323  }
   324  
   325  // encStructTerminator encodes the end of an encoded struct
   326  // as delta field number of 0.
   327  func encStructTerminator(i *encInstr, state *encoderState, p unsafe.Pointer) {
   328  	state.encodeUint(0)
   329  }
   330  
   331  // Execution engine
   332  
   333  // encEngine an array of instructions indexed by field number of the encoding
   334  // data, typically a struct.  It is executed top to bottom, walking the struct.
   335  type encEngine struct {
   336  	instr []encInstr
   337  }
   338  
   339  const singletonField = 0
   340  
   341  // encodeSingle encodes a single top-level non-struct value.
   342  func (enc *Encoder) encodeSingle(b *bytes.Buffer, engine *encEngine, basep unsafe.Pointer) {
   343  	state := enc.newEncoderState(b)
   344  	state.fieldnum = singletonField
   345  	// There is no surrounding struct to frame the transmission, so we must
   346  	// generate data even if the item is zero.  To do this, set sendZero.
   347  	state.sendZero = true
   348  	instr := &engine.instr[singletonField]
   349  	p := basep // offset will be zero
   350  	if instr.indir > 0 {
   351  		if p = encIndirect(p, instr.indir); p == nil {
   352  			return
   353  		}
   354  	}
   355  	instr.op(instr, state, p)
   356  	enc.freeEncoderState(state)
   357  }
   358  
   359  // encodeStruct encodes a single struct value.
   360  func (enc *Encoder) encodeStruct(b *bytes.Buffer, engine *encEngine, basep unsafe.Pointer) {
   361  	state := enc.newEncoderState(b)
   362  	state.fieldnum = -1
   363  	for i := 0; i < len(engine.instr); i++ {
   364  		instr := &engine.instr[i]
   365  		p := unsafe.Pointer(uintptr(basep) + instr.offset)
   366  		if instr.indir > 0 {
   367  			if p = encIndirect(p, instr.indir); p == nil {
   368  				continue
   369  			}
   370  		}
   371  		instr.op(instr, state, p)
   372  	}
   373  	enc.freeEncoderState(state)
   374  }
   375  
   376  // encodeArray encodes the array whose 0th element is at p.
   377  func (enc *Encoder) encodeArray(b *bytes.Buffer, p unsafe.Pointer, op encOp, elemWid uintptr, elemIndir int, length int) {
   378  	state := enc.newEncoderState(b)
   379  	state.fieldnum = -1
   380  	state.sendZero = true
   381  	state.encodeUint(uint64(length))
   382  	for i := 0; i < length; i++ {
   383  		elemp := p
   384  		if elemIndir > 0 {
   385  			up := encIndirect(elemp, elemIndir)
   386  			if up == nil {
   387  				errorf("encodeArray: nil element")
   388  			}
   389  			elemp = up
   390  		}
   391  		op(nil, state, elemp)
   392  		p = unsafe.Pointer(uintptr(p) + elemWid)
   393  	}
   394  	enc.freeEncoderState(state)
   395  }
   396  
   397  // encodeReflectValue is a helper for maps. It encodes the value v.
   398  func encodeReflectValue(state *encoderState, v reflect.Value, op encOp, indir int) {
   399  	for i := 0; i < indir && v.IsValid(); i++ {
   400  		v = reflect.Indirect(v)
   401  	}
   402  	if !v.IsValid() {
   403  		errorf("encodeReflectValue: nil element")
   404  	}
   405  	op(nil, state, unsafeAddr(v))
   406  }
   407  
   408  // encodeMap encodes a map as unsigned count followed by key:value pairs.
   409  // Because map internals are not exposed, we must use reflection rather than
   410  // addresses.
   411  func (enc *Encoder) encodeMap(b *bytes.Buffer, mv reflect.Value, keyOp, elemOp encOp, keyIndir, elemIndir int) {
   412  	state := enc.newEncoderState(b)
   413  	state.fieldnum = -1
   414  	state.sendZero = true
   415  	keys := mv.MapKeys()
   416  	state.encodeUint(uint64(len(keys)))
   417  	for _, key := range keys {
   418  		encodeReflectValue(state, key, keyOp, keyIndir)
   419  		encodeReflectValue(state, mv.MapIndex(key), elemOp, elemIndir)
   420  	}
   421  	enc.freeEncoderState(state)
   422  }
   423  
   424  // encodeInterface encodes the interface value iv.
   425  // To send an interface, we send a string identifying the concrete type, followed
   426  // by the type identifier (which might require defining that type right now), followed
   427  // by the concrete value.  A nil value gets sent as the empty string for the name,
   428  // followed by no value.
   429  func (enc *Encoder) encodeInterface(b *bytes.Buffer, iv reflect.Value) {
   430  	// Gobs can encode nil interface values but not typed interface
   431  	// values holding nil pointers, since nil pointers point to no value.
   432  	elem := iv.Elem()
   433  	if elem.Kind() == reflect.Ptr && elem.IsNil() {
   434  		errorf("gob: cannot encode nil pointer of type %s inside interface", iv.Elem().Type())
   435  	}
   436  	state := enc.newEncoderState(b)
   437  	state.fieldnum = -1
   438  	state.sendZero = true
   439  	if iv.IsNil() {
   440  		state.encodeUint(0)
   441  		return
   442  	}
   443  
   444  	ut := userType(iv.Elem().Type())
   445  	registerLock.RLock()
   446  	name, ok := concreteTypeToName[ut.base]
   447  	registerLock.RUnlock()
   448  	if !ok {
   449  		errorf("type not registered for interface: %s", ut.base)
   450  	}
   451  	// Send the name.
   452  	state.encodeUint(uint64(len(name)))
   453  	_, err := state.b.WriteString(name)
   454  	if err != nil {
   455  		error_(err)
   456  	}
   457  	// Define the type id if necessary.
   458  	enc.sendTypeDescriptor(enc.writer(), state, ut)
   459  	// Send the type id.
   460  	enc.sendTypeId(state, ut)
   461  	// Encode the value into a new buffer.  Any nested type definitions
   462  	// should be written to b, before the encoded value.
   463  	enc.pushWriter(b)
   464  	data := new(bytes.Buffer)
   465  	data.Write(spaceForLength)
   466  	enc.encode(data, elem, ut)
   467  	if enc.err != nil {
   468  		error_(enc.err)
   469  	}
   470  	enc.popWriter()
   471  	enc.writeMessage(b, data)
   472  	if enc.err != nil {
   473  		error_(err)
   474  	}
   475  	enc.freeEncoderState(state)
   476  }
   477  
   478  // isZero reports whether the value is the zero of its type.
   479  func isZero(val reflect.Value) bool {
   480  	switch val.Kind() {
   481  	case reflect.Array:
   482  		for i := 0; i < val.Len(); i++ {
   483  			if !isZero(val.Index(i)) {
   484  				return false
   485  			}
   486  		}
   487  		return true
   488  	case reflect.Map, reflect.Slice, reflect.String:
   489  		return val.Len() == 0
   490  	case reflect.Bool:
   491  		return !val.Bool()
   492  	case reflect.Complex64, reflect.Complex128:
   493  		return val.Complex() == 0
   494  	case reflect.Chan, reflect.Func, reflect.Ptr:
   495  		return val.IsNil()
   496  	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
   497  		return val.Int() == 0
   498  	case reflect.Float32, reflect.Float64:
   499  		return val.Float() == 0
   500  	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
   501  		return val.Uint() == 0
   502  	case reflect.Struct:
   503  		for i := 0; i < val.NumField(); i++ {
   504  			if !isZero(val.Field(i)) {
   505  				return false
   506  			}
   507  		}
   508  		return true
   509  	}
   510  	panic("unknown type in isZero " + val.Type().String())
   511  }
   512  
   513  // encGobEncoder encodes a value that implements the GobEncoder interface.
   514  // The data is sent as a byte array.
   515  func (enc *Encoder) encodeGobEncoder(b *bytes.Buffer, ut *userTypeInfo, v reflect.Value) {
   516  	// TODO: should we catch panics from the called method?
   517  
   518  	var data []byte
   519  	var err error
   520  	// We know it's one of these.
   521  	switch ut.externalEnc {
   522  	case xGob:
   523  		data, err = v.Interface().(GobEncoder).GobEncode()
   524  	case xBinary:
   525  		data, err = v.Interface().(encoding.BinaryMarshaler).MarshalBinary()
   526  	case xText:
   527  		data, err = v.Interface().(encoding.TextMarshaler).MarshalText()
   528  	}
   529  	if err != nil {
   530  		error_(err)
   531  	}
   532  	state := enc.newEncoderState(b)
   533  	state.fieldnum = -1
   534  	state.encodeUint(uint64(len(data)))
   535  	state.b.Write(data)
   536  	enc.freeEncoderState(state)
   537  }
   538  
   539  var encOpTable = [...]encOp{
   540  	reflect.Bool:       encBool,
   541  	reflect.Int:        encInt,
   542  	reflect.Int8:       encInt8,
   543  	reflect.Int16:      encInt16,
   544  	reflect.Int32:      encInt32,
   545  	reflect.Int64:      encInt64,
   546  	reflect.Uint:       encUint,
   547  	reflect.Uint8:      encUint8,
   548  	reflect.Uint16:     encUint16,
   549  	reflect.Uint32:     encUint32,
   550  	reflect.Uint64:     encUint64,
   551  	reflect.Uintptr:    encUintptr,
   552  	reflect.Float32:    encFloat32,
   553  	reflect.Float64:    encFloat64,
   554  	reflect.Complex64:  encComplex64,
   555  	reflect.Complex128: encComplex128,
   556  	reflect.String:     encString,
   557  }
   558  
   559  // encOpFor returns (a pointer to) the encoding op for the base type under rt and
   560  // the indirection count to reach it.
   561  func (enc *Encoder) encOpFor(rt reflect.Type, inProgress map[reflect.Type]*encOp) (*encOp, int) {
   562  	ut := userType(rt)
   563  	// If the type implements GobEncoder, we handle it without further processing.
   564  	if ut.externalEnc != 0 {
   565  		return enc.gobEncodeOpFor(ut)
   566  	}
   567  	// If this type is already in progress, it's a recursive type (e.g. map[string]*T).
   568  	// Return the pointer to the op we're already building.
   569  	if opPtr := inProgress[rt]; opPtr != nil {
   570  		return opPtr, ut.indir
   571  	}
   572  	typ := ut.base
   573  	indir := ut.indir
   574  	k := typ.Kind()
   575  	var op encOp
   576  	if int(k) < len(encOpTable) {
   577  		op = encOpTable[k]
   578  	}
   579  	if op == nil {
   580  		inProgress[rt] = &op
   581  		// Special cases
   582  		switch t := typ; t.Kind() {
   583  		case reflect.Slice:
   584  			if t.Elem().Kind() == reflect.Uint8 {
   585  				op = encUint8Array
   586  				break
   587  			}
   588  			// Slices have a header; we decode it to find the underlying array.
   589  			elemOp, elemIndir := enc.encOpFor(t.Elem(), inProgress)
   590  			op = func(i *encInstr, state *encoderState, p unsafe.Pointer) {
   591  				slice := (*reflect.SliceHeader)(p)
   592  				if !state.sendZero && slice.Len == 0 {
   593  					return
   594  				}
   595  				state.update(i)
   596  				state.enc.encodeArray(state.b, unsafe.Pointer(slice.Data), *elemOp, t.Elem().Size(), elemIndir, int(slice.Len))
   597  			}
   598  		case reflect.Array:
   599  			// True arrays have size in the type.
   600  			elemOp, elemIndir := enc.encOpFor(t.Elem(), inProgress)
   601  			op = func(i *encInstr, state *encoderState, p unsafe.Pointer) {
   602  				state.update(i)
   603  				state.enc.encodeArray(state.b, p, *elemOp, t.Elem().Size(), elemIndir, t.Len())
   604  			}
   605  		case reflect.Map:
   606  			keyOp, keyIndir := enc.encOpFor(t.Key(), inProgress)
   607  			elemOp, elemIndir := enc.encOpFor(t.Elem(), inProgress)
   608  			op = func(i *encInstr, state *encoderState, p unsafe.Pointer) {
   609  				// Maps cannot be accessed by moving addresses around the way
   610  				// that slices etc. can.  We must recover a full reflection value for
   611  				// the iteration.
   612  				v := reflect.NewAt(t, unsafe.Pointer(p)).Elem()
   613  				mv := reflect.Indirect(v)
   614  				// We send zero-length (but non-nil) maps because the
   615  				// receiver might want to use the map.  (Maps don't use append.)
   616  				if !state.sendZero && mv.IsNil() {
   617  					return
   618  				}
   619  				state.update(i)
   620  				state.enc.encodeMap(state.b, mv, *keyOp, *elemOp, keyIndir, elemIndir)
   621  			}
   622  		case reflect.Struct:
   623  			// Generate a closure that calls out to the engine for the nested type.
   624  			enc.getEncEngine(userType(typ))
   625  			info := mustGetTypeInfo(typ)
   626  			op = func(i *encInstr, state *encoderState, p unsafe.Pointer) {
   627  				state.update(i)
   628  				// indirect through info to delay evaluation for recursive structs
   629  				state.enc.encodeStruct(state.b, info.encoder, p)
   630  			}
   631  		case reflect.Interface:
   632  			op = func(i *encInstr, state *encoderState, p unsafe.Pointer) {
   633  				// Interfaces transmit the name and contents of the concrete
   634  				// value they contain.
   635  				v := reflect.NewAt(t, unsafe.Pointer(p)).Elem()
   636  				iv := reflect.Indirect(v)
   637  				if !state.sendZero && (!iv.IsValid() || iv.IsNil()) {
   638  					return
   639  				}
   640  				state.update(i)
   641  				state.enc.encodeInterface(state.b, iv)
   642  			}
   643  		}
   644  	}
   645  	if op == nil {
   646  		errorf("can't happen: encode type %s", rt)
   647  	}
   648  	return &op, indir
   649  }
   650  
   651  // gobEncodeOpFor returns the op for a type that is known to implement
   652  // GobEncoder.
   653  func (enc *Encoder) gobEncodeOpFor(ut *userTypeInfo) (*encOp, int) {
   654  	rt := ut.user
   655  	if ut.encIndir == -1 {
   656  		rt = reflect.PtrTo(rt)
   657  	} else if ut.encIndir > 0 {
   658  		for i := int8(0); i < ut.encIndir; i++ {
   659  			rt = rt.Elem()
   660  		}
   661  	}
   662  	var op encOp
   663  	op = func(i *encInstr, state *encoderState, p unsafe.Pointer) {
   664  		var v reflect.Value
   665  		if ut.encIndir == -1 {
   666  			// Need to climb up one level to turn value into pointer.
   667  			v = reflect.NewAt(rt, unsafe.Pointer(&p)).Elem()
   668  		} else {
   669  			v = reflect.NewAt(rt, p).Elem()
   670  		}
   671  		if !state.sendZero && isZero(v) {
   672  			return
   673  		}
   674  		state.update(i)
   675  		state.enc.encodeGobEncoder(state.b, ut, v)
   676  	}
   677  	return &op, int(ut.encIndir) // encIndir: op will get called with p == address of receiver.
   678  }
   679  
   680  // compileEnc returns the engine to compile the type.
   681  func (enc *Encoder) compileEnc(ut *userTypeInfo) *encEngine {
   682  	srt := ut.base
   683  	engine := new(encEngine)
   684  	seen := make(map[reflect.Type]*encOp)
   685  	rt := ut.base
   686  	if ut.externalEnc != 0 {
   687  		rt = ut.user
   688  	}
   689  	if ut.externalEnc == 0 && srt.Kind() == reflect.Struct {
   690  		for fieldNum, wireFieldNum := 0, 0; fieldNum < srt.NumField(); fieldNum++ {
   691  			f := srt.Field(fieldNum)
   692  			if !isSent(&f) {
   693  				continue
   694  			}
   695  			op, indir := enc.encOpFor(f.Type, seen)
   696  			engine.instr = append(engine.instr, encInstr{*op, wireFieldNum, indir, uintptr(f.Offset)})
   697  			wireFieldNum++
   698  		}
   699  		if srt.NumField() > 0 && len(engine.instr) == 0 {
   700  			errorf("type %s has no exported fields", rt)
   701  		}
   702  		engine.instr = append(engine.instr, encInstr{encStructTerminator, 0, 0, 0})
   703  	} else {
   704  		engine.instr = make([]encInstr, 1)
   705  		op, indir := enc.encOpFor(rt, seen)
   706  		engine.instr[0] = encInstr{*op, singletonField, indir, 0} // offset is zero
   707  	}
   708  	return engine
   709  }
   710  
   711  // getEncEngine returns the engine to compile the type.
   712  // typeLock must be held (or we're in initialization and guaranteed single-threaded).
   713  func (enc *Encoder) getEncEngine(ut *userTypeInfo) *encEngine {
   714  	info, err1 := getTypeInfo(ut)
   715  	if err1 != nil {
   716  		error_(err1)
   717  	}
   718  	if info.encoder == nil {
   719  		// Assign the encEngine now, so recursive types work correctly. But...
   720  		info.encoder = new(encEngine)
   721  		// ... if we fail to complete building the engine, don't cache the half-built machine.
   722  		// Doing this here means we won't cache a type that is itself OK but
   723  		// that contains a nested type that won't compile. The result is consistent
   724  		// error behavior when Encode is called multiple times on the top-level type.
   725  		ok := false
   726  		defer func() {
   727  			if !ok {
   728  				info.encoder = nil
   729  			}
   730  		}()
   731  		info.encoder = enc.compileEnc(ut)
   732  		ok = true
   733  	}
   734  	return info.encoder
   735  }
   736  
   737  // lockAndGetEncEngine is a function that locks and compiles.
   738  // This lets us hold the lock only while compiling, not when encoding.
   739  func (enc *Encoder) lockAndGetEncEngine(ut *userTypeInfo) *encEngine {
   740  	typeLock.Lock()
   741  	defer typeLock.Unlock()
   742  	return enc.getEncEngine(ut)
   743  }
   744  
   745  func (enc *Encoder) encode(b *bytes.Buffer, value reflect.Value, ut *userTypeInfo) {
   746  	defer catchError(&enc.err)
   747  	engine := enc.lockAndGetEncEngine(ut)
   748  	indir := ut.indir
   749  	if ut.externalEnc != 0 {
   750  		indir = int(ut.encIndir)
   751  	}
   752  	for i := 0; i < indir; i++ {
   753  		value = reflect.Indirect(value)
   754  	}
   755  	if ut.externalEnc == 0 && value.Type().Kind() == reflect.Struct {
   756  		enc.encodeStruct(b, engine, unsafeAddr(value))
   757  	} else {
   758  		enc.encodeSingle(b, engine, unsafeAddr(value))
   759  	}
   760  }