encode.go 20 KB
Newer Older
1 2 3 4
// 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.

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

7 8 9
package gob

import (
10
	"encoding"
11
	"encoding/binary"
12
	"math"
13
	"math/bits"
14
	"reflect"
15
	"sync"
16 17
)

18 19 20
const uint64Size = 8

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

22
// encoderState is the global execution state of an instance of the encoder.
23 24 25 26 27
// 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
28
	b        *encBuffer
29 30 31
	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.
32
	next     *encoderState        // for free list
33 34
}

35 36 37 38 39 40 41
// 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
}

42 43 44 45 46 47 48 49
var encBufferPool = sync.Pool{
	New: func() interface{} {
		e := new(encBuffer)
		e.data = e.scratch[0:0]
		return e
	},
}

50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
func (e *encBuffer) WriteByte(c byte) {
	e.data = append(e.data, c)
}

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

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

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

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

func (e *encBuffer) Reset() {
72 73 74 75 76
	if len(e.data) >= tooBig {
		e.data = e.scratch[0:0]
	} else {
		e.data = e.data[0:0]
	}
77 78 79
}

func (enc *Encoder) newEncoderState(b *encBuffer) *encoderState {
80 81 82 83 84 85 86 87 88 89
	e := enc.freeList
	if e == nil {
		e = new(encoderState)
		e.enc = enc
	} else {
		enc.freeList = e.next
	}
	e.sendZero = false
	e.fieldnum = 0
	e.b = b
90 91 92
	if len(b.data) == 0 {
		b.data = b.scratch[0:0]
	}
93 94 95 96 97 98
	return e
}

func (enc *Encoder) freeEncoderState(e *encoderState) {
	e.next = enc.freeList
	enc.freeList = e
99 100
}

101
// Unsigned integers have a two-state encoding. If the number is less
102 103 104 105 106
// 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.
107
func (state *encoderState) encodeUint(x uint64) {
108
	if x <= 0x7F {
109
		state.b.WriteByte(uint8(x))
110 111
		return
	}
112 113 114 115 116 117

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

	state.b.Write(state.buf[bc : uint64Size+1])
118 119 120 121 122
}

// 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.
123
func (state *encoderState) encodeInt(i int64) {
124 125 126 127 128 129
	var x uint64
	if i < 0 {
		x = uint64(^i<<1) | 1
	} else {
		x = uint64(i << 1)
	}
130
	state.encodeUint(x)
131 132
}

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

// The 'instructions' of the encoding machine
type encInstr struct {
138 139 140 141
	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
142 143
}

144 145
// 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
146 147
func (state *encoderState) update(instr *encInstr) {
	if instr != nil {
148
		state.encodeUint(uint64(instr.field - state.fieldnum))
149 150 151 152
		state.fieldnum = instr.field
	}
}

153 154
// Each encoder for a composite is responsible for handling any
// indirections associated with the elements of the data structure.
155 156
// If any pointer so reached is nil, no bytes are written. If the
// data item is zero, no bytes are written. Single values - ints,
157 158 159 160
// 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.
161

162 163
// encIndirect dereferences pv indir times and returns the result.
func encIndirect(pv reflect.Value, indir int) reflect.Value {
164
	for ; indir > 0; indir-- {
165 166
		if pv.IsNil() {
			break
167
		}
168
		pv = pv.Elem()
169
	}
170
	return pv
171 172
}

173 174 175
// encBool encodes the bool referenced by v as an unsigned 0 or 1.
func encBool(i *encInstr, state *encoderState, v reflect.Value) {
	b := v.Bool()
176 177 178
	if b || state.sendZero {
		state.update(i)
		if b {
179
			state.encodeUint(1)
180
		} else {
181
			state.encodeUint(0)
182 183 184 185
		}
	}
}

186 187 188 189
// encInt encodes the signed integer (int int8 int16 int32 int64) referenced by v.
func encInt(i *encInstr, state *encoderState, v reflect.Value) {
	value := v.Int()
	if value != 0 || state.sendZero {
190
		state.update(i)
191
		state.encodeInt(value)
192 193 194
	}
}

195 196 197 198
// encUint encodes the unsigned integer (uint uint8 uint16 uint32 uint64 uintptr) referenced by v.
func encUint(i *encInstr, state *encoderState, v reflect.Value) {
	value := v.Uint()
	if value != 0 || state.sendZero {
199
		state.update(i)
200
		state.encodeUint(value)
201 202 203
	}
}

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

215 216 217
// encFloat encodes the floating point value (float32 float64) referenced by v.
func encFloat(i *encInstr, state *encoderState, v reflect.Value) {
	f := v.Float()
218
	if f != 0 || state.sendZero {
219
		bits := floatBits(f)
220
		state.update(i)
221
		state.encodeUint(bits)
222 223 224
	}
}

225
// encComplex encodes the complex value (complex64 complex128) referenced by v.
226
// Complex numbers are just a pair of floating-point numbers, real part first.
227 228
func encComplex(i *encInstr, state *encoderState, v reflect.Value) {
	c := v.Complex()
229 230 231 232
	if c != 0+0i || state.sendZero {
		rpart := floatBits(real(c))
		ipart := floatBits(imag(c))
		state.update(i)
233 234
		state.encodeUint(rpart)
		state.encodeUint(ipart)
235 236 237
	}
}

238
// encUint8Array encodes the byte array referenced by v.
239
// Byte arrays are encoded as an unsigned count followed by the raw bytes.
240 241
func encUint8Array(i *encInstr, state *encoderState, v reflect.Value) {
	b := v.Bytes()
242 243
	if len(b) > 0 || state.sendZero {
		state.update(i)
244
		state.encodeUint(uint64(len(b)))
245 246 247 248
		state.b.Write(b)
	}
}

249
// encString encodes the string referenced by v.
250
// Strings are encoded as an unsigned count followed by the raw bytes.
251 252
func encString(i *encInstr, state *encoderState, v reflect.Value) {
	s := v.String()
253 254
	if len(s) > 0 || state.sendZero {
		state.update(i)
255
		state.encodeUint(uint64(len(s)))
256
		state.b.WriteString(s)
257 258 259
	}
}

260 261
// encStructTerminator encodes the end of an encoded struct
// as delta field number of 0.
262
func encStructTerminator(i *encInstr, state *encoderState, v reflect.Value) {
263
	state.encodeUint(0)
264 265 266 267
}

// Execution engine

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

const singletonField = 0

276 277 278 279 280 281 282 283 284 285 286 287
// valid reports whether the value is valid and a non-nil pointer.
// (Slices, maps, and chans take care of themselves.)
func valid(v reflect.Value) bool {
	switch v.Kind() {
	case reflect.Invalid:
		return false
	case reflect.Ptr:
		return !v.IsNil()
	}
	return true
}

288
// encodeSingle encodes a single top-level non-struct value.
289
func (enc *Encoder) encodeSingle(b *encBuffer, engine *encEngine, value reflect.Value) {
290
	state := enc.newEncoderState(b)
291
	defer enc.freeEncoderState(state)
292 293
	state.fieldnum = singletonField
	// There is no surrounding struct to frame the transmission, so we must
294
	// generate data even if the item is zero. To do this, set sendZero.
295 296 297
	state.sendZero = true
	instr := &engine.instr[singletonField]
	if instr.indir > 0 {
298 299 300 301
		value = encIndirect(value, instr.indir)
	}
	if valid(value) {
		instr.op(instr, state, value)
302 303 304
	}
}

305
// encodeStruct encodes a single struct value.
306 307 308 309
func (enc *Encoder) encodeStruct(b *encBuffer, engine *encEngine, value reflect.Value) {
	if !valid(value) {
		return
	}
310
	state := enc.newEncoderState(b)
311
	defer enc.freeEncoderState(state)
312 313 314
	state.fieldnum = -1
	for i := 0; i < len(engine.instr); i++ {
		instr := &engine.instr[i]
315 316 317 318 319 320
		if i >= value.NumField() {
			// encStructTerminator
			instr.op(instr, state, reflect.Value{})
			break
		}
		field := value.FieldByIndex(instr.index)
321
		if instr.indir > 0 {
322 323 324
			field = encIndirect(field, instr.indir)
			// TODO: Is field guaranteed valid? If so we could avoid this check.
			if !valid(field) {
325 326 327
				continue
			}
		}
328
		instr.op(instr, state, field)
329 330 331
	}
}

332 333
// encodeArray encodes an array.
func (enc *Encoder) encodeArray(b *encBuffer, value reflect.Value, op encOp, elemIndir int, length int, helper encHelper) {
334
	state := enc.newEncoderState(b)
335
	defer enc.freeEncoderState(state)
336 337
	state.fieldnum = -1
	state.sendZero = true
338
	state.encodeUint(uint64(length))
339 340 341
	if helper != nil && helper(state, value) {
		return
	}
342
	for i := 0; i < length; i++ {
343
		elem := value.Index(i)
344
		if elemIndir > 0 {
345 346 347
			elem = encIndirect(elem, elemIndir)
			// TODO: Is elem guaranteed valid? If so we could avoid this check.
			if !valid(elem) {
348
				errorf("encodeArray: nil element")
349 350
			}
		}
351
		op(nil, state, elem)
352 353 354
	}
}

355
// encodeReflectValue is a helper for maps. It encodes the value v.
356
func encodeReflectValue(state *encoderState, v reflect.Value, op encOp, indir int) {
357
	for i := 0; i < indir && v.IsValid(); i++ {
358 359
		v = reflect.Indirect(v)
	}
360 361
	if !v.IsValid() {
		errorf("encodeReflectValue: nil element")
362
	}
363
	op(nil, state, v)
364 365
}

366
// encodeMap encodes a map as unsigned count followed by key:value pairs.
367
func (enc *Encoder) encodeMap(b *encBuffer, mv reflect.Value, keyOp, elemOp encOp, keyIndir, elemIndir int) {
368
	state := enc.newEncoderState(b)
369 370
	state.fieldnum = -1
	state.sendZero = true
371
	keys := mv.MapKeys()
372
	state.encodeUint(uint64(len(keys)))
373 374
	for _, key := range keys {
		encodeReflectValue(state, key, keyOp, keyIndir)
375
		encodeReflectValue(state, mv.MapIndex(key), elemOp, elemIndir)
376
	}
377
	enc.freeEncoderState(state)
378 379
}

380
// encodeInterface encodes the interface value iv.
381 382
// 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
383
// by the concrete value. A nil value gets sent as the empty string for the name,
384
// followed by no value.
385
func (enc *Encoder) encodeInterface(b *encBuffer, iv reflect.Value) {
386 387 388 389 390 391
	// Gobs can encode nil interface values but not typed interface
	// values holding nil pointers, since nil pointers point to no value.
	elem := iv.Elem()
	if elem.Kind() == reflect.Ptr && elem.IsNil() {
		errorf("gob: cannot encode nil pointer of type %s inside interface", iv.Elem().Type())
	}
392
	state := enc.newEncoderState(b)
393 394 395
	state.fieldnum = -1
	state.sendZero = true
	if iv.IsNil() {
396
		state.encodeUint(0)
397 398 399
		return
	}

400
	ut := userType(iv.Elem().Type())
401
	namei, ok := concreteTypeToName.Load(ut.base)
402
	if !ok {
403
		errorf("type not registered for interface: %s", ut.base)
404
	}
405 406
	name := namei.(string)

407
	// Send the name.
408
	state.encodeUint(uint64(len(name)))
409
	state.b.WriteString(name)
410 411 412 413
	// Define the type id if necessary.
	enc.sendTypeDescriptor(enc.writer(), state, ut)
	// Send the type id.
	enc.sendTypeId(state, ut)
414
	// Encode the value into a new buffer. Any nested type definitions
415 416
	// should be written to b, before the encoded value.
	enc.pushWriter(b)
417
	data := encBufferPool.Get().(*encBuffer)
418
	data.Write(spaceForLength)
419
	enc.encode(data, elem, ut)
420
	if enc.err != nil {
421
		error_(enc.err)
422
	}
423 424
	enc.popWriter()
	enc.writeMessage(b, data)
425 426
	data.Reset()
	encBufferPool.Put(data)
427
	if enc.err != nil {
428
		error_(enc.err)
429
	}
430 431 432
	enc.freeEncoderState(state)
}

433
// isZero reports whether the value is the zero of its type.
434 435
func isZero(val reflect.Value) bool {
	switch val.Kind() {
436 437 438 439 440 441 442 443
	case reflect.Array:
		for i := 0; i < val.Len(); i++ {
			if !isZero(val.Index(i)) {
				return false
			}
		}
		return true
	case reflect.Map, reflect.Slice, reflect.String:
444 445 446 447 448
		return val.Len() == 0
	case reflect.Bool:
		return !val.Bool()
	case reflect.Complex64, reflect.Complex128:
		return val.Complex() == 0
449
	case reflect.Chan, reflect.Func, reflect.Interface, reflect.Ptr:
450 451 452 453 454 455 456
		return val.IsNil()
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return val.Int() == 0
	case reflect.Float32, reflect.Float64:
		return val.Float() == 0
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		return val.Uint() == 0
457 458 459 460 461 462 463
	case reflect.Struct:
		for i := 0; i < val.NumField(); i++ {
			if !isZero(val.Field(i)) {
				return false
			}
		}
		return true
464 465 466 467
	}
	panic("unknown type in isZero " + val.Type().String())
}

468 469
// encGobEncoder encodes a value that implements the GobEncoder interface.
// The data is sent as a byte array.
470
func (enc *Encoder) encodeGobEncoder(b *encBuffer, ut *userTypeInfo, v reflect.Value) {
471
	// TODO: should we catch panics from the called method?
472 473 474 475 476 477 478 479 480 481 482 483

	var data []byte
	var err error
	// We know it's one of these.
	switch ut.externalEnc {
	case xGob:
		data, err = v.Interface().(GobEncoder).GobEncode()
	case xBinary:
		data, err = v.Interface().(encoding.BinaryMarshaler).MarshalBinary()
	case xText:
		data, err = v.Interface().(encoding.TextMarshaler).MarshalText()
	}
484
	if err != nil {
485
		error_(err)
486 487 488 489 490 491
	}
	state := enc.newEncoderState(b)
	state.fieldnum = -1
	state.encodeUint(uint64(len(data)))
	state.b.Write(data)
	enc.freeEncoderState(state)
492 493
}

494
var encOpTable = [...]encOp{
495 496
	reflect.Bool:       encBool,
	reflect.Int:        encInt,
497 498 499 500
	reflect.Int8:       encInt,
	reflect.Int16:      encInt,
	reflect.Int32:      encInt,
	reflect.Int64:      encInt,
501
	reflect.Uint:       encUint,
502 503 504 505 506 507 508 509 510
	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,
511 512 513
	reflect.String:     encString,
}

514
// encOpFor returns (a pointer to) the encoding op for the base type under rt and
515
// the indirection count to reach it.
516
func encOpFor(rt reflect.Type, inProgress map[reflect.Type]*encOp, building map[*typeInfo]bool) (*encOp, int) {
517
	ut := userType(rt)
518
	// If the type implements GobEncoder, we handle it without further processing.
519
	if ut.externalEnc != 0 {
520
		return gobEncodeOpFor(ut)
521
	}
522 523 524 525 526 527 528
	// 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 opPtr := inProgress[rt]; opPtr != nil {
		return opPtr, ut.indir
	}
	typ := ut.base
	indir := ut.indir
529
	k := typ.Kind()
530 531 532
	var op encOp
	if int(k) < len(encOpTable) {
		op = encOpTable[k]
533 534
	}
	if op == nil {
535
		inProgress[rt] = &op
536
		// Special cases
537 538
		switch t := typ; t.Kind() {
		case reflect.Slice:
539 540 541 542 543
			if t.Elem().Kind() == reflect.Uint8 {
				op = encUint8Array
				break
			}
			// Slices have a header; we decode it to find the underlying array.
544 545 546 547
			elemOp, elemIndir := encOpFor(t.Elem(), inProgress, building)
			helper := encSliceHelper[t.Elem().Kind()]
			op = func(i *encInstr, state *encoderState, slice reflect.Value) {
				if !state.sendZero && slice.Len() == 0 {
548 549 550
					return
				}
				state.update(i)
551
				state.enc.encodeArray(state.b, slice, *elemOp, elemIndir, slice.Len(), helper)
552
			}
553
		case reflect.Array:
554
			// True arrays have size in the type.
555 556 557
			elemOp, elemIndir := encOpFor(t.Elem(), inProgress, building)
			helper := encArrayHelper[t.Elem().Kind()]
			op = func(i *encInstr, state *encoderState, array reflect.Value) {
558
				state.update(i)
559
				state.enc.encodeArray(state.b, array, *elemOp, elemIndir, array.Len(), helper)
560
			}
561
		case reflect.Map:
562 563 564
			keyOp, keyIndir := encOpFor(t.Key(), inProgress, building)
			elemOp, elemIndir := encOpFor(t.Elem(), inProgress, building)
			op = func(i *encInstr, state *encoderState, mv reflect.Value) {
565 566 567
				// We send zero-length (but non-nil) maps because the
				// receiver might want to use the map.  (Maps don't use append.)
				if !state.sendZero && mv.IsNil() {
568 569 570
					return
				}
				state.update(i)
571
				state.enc.encodeMap(state.b, mv, *keyOp, *elemOp, keyIndir, elemIndir)
572
			}
573
		case reflect.Struct:
574
			// Generate a closure that calls out to the engine for the nested type.
575
			getEncEngine(userType(typ), building)
576
			info := mustGetTypeInfo(typ)
577
			op = func(i *encInstr, state *encoderState, sv reflect.Value) {
578 579
				state.update(i)
				// indirect through info to delay evaluation for recursive structs
580 581
				enc := info.encoder.Load().(*encEngine)
				state.enc.encodeStruct(state.b, enc, sv)
582
			}
583
		case reflect.Interface:
584
			op = func(i *encInstr, state *encoderState, iv reflect.Value) {
585
				if !state.sendZero && (!iv.IsValid() || iv.IsNil()) {
586 587 588 589 590 591 592 593
					return
				}
				state.update(i)
				state.enc.encodeInterface(state.b, iv)
			}
		}
	}
	if op == nil {
594
		errorf("can't happen: encode type %s", rt)
595
	}
596
	return &op, indir
597 598
}

599 600
// gobEncodeOpFor returns the op for a type that is known to implement GobEncoder.
func gobEncodeOpFor(ut *userTypeInfo) (*encOp, int) {
601 602 603 604 605
	rt := ut.user
	if ut.encIndir == -1 {
		rt = reflect.PtrTo(rt)
	} else if ut.encIndir > 0 {
		for i := int8(0); i < ut.encIndir; i++ {
606
			rt = rt.Elem()
607 608 609
		}
	}
	var op encOp
610
	op = func(i *encInstr, state *encoderState, v reflect.Value) {
611 612
		if ut.encIndir == -1 {
			// Need to climb up one level to turn value into pointer.
613 614 615 616
			if !v.CanAddr() {
				errorf("unaddressable value of type %s", rt)
			}
			v = v.Addr()
617
		}
618 619 620
		if !state.sendZero && isZero(v) {
			return
		}
621
		state.update(i)
622
		state.enc.encodeGobEncoder(state.b, ut, v)
623 624 625 626 627
	}
	return &op, int(ut.encIndir) // encIndir: op will get called with p == address of receiver.
}

// compileEnc returns the engine to compile the type.
628
func compileEnc(ut *userTypeInfo, building map[*typeInfo]bool) *encEngine {
629
	srt := ut.base
630
	engine := new(encEngine)
631
	seen := make(map[reflect.Type]*encOp)
632
	rt := ut.base
633
	if ut.externalEnc != 0 {
634 635
		rt = ut.user
	}
636
	if ut.externalEnc == 0 && srt.Kind() == reflect.Struct {
637
		for fieldNum, wireFieldNum := 0, 0; fieldNum < srt.NumField(); fieldNum++ {
638
			f := srt.Field(fieldNum)
639
			if !isSent(&f) {
640
				continue
641
			}
642 643
			op, indir := encOpFor(f.Type, seen, building)
			engine.instr = append(engine.instr, encInstr{*op, wireFieldNum, f.Index, indir})
644
			wireFieldNum++
645 646
		}
		if srt.NumField() > 0 && len(engine.instr) == 0 {
647
			errorf("type %s has no exported fields", rt)
648
		}
649
		engine.instr = append(engine.instr, encInstr{encStructTerminator, 0, nil, 0})
650 651
	} else {
		engine.instr = make([]encInstr, 1)
652 653
		op, indir := encOpFor(rt, seen, building)
		engine.instr[0] = encInstr{*op, singletonField, nil, indir}
654 655 656 657
	}
	return engine
}

658
// getEncEngine returns the engine to compile the type.
659 660 661 662
func getEncEngine(ut *userTypeInfo, building map[*typeInfo]bool) *encEngine {
	info, err := getTypeInfo(ut)
	if err != nil {
		error_(err)
663
	}
664 665 666 667 668
	enc, ok := info.encoder.Load().(*encEngine)
	if !ok {
		enc = buildEncEngine(info, ut, building)
	}
	return enc
669 670
}

671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
func buildEncEngine(info *typeInfo, ut *userTypeInfo, building map[*typeInfo]bool) *encEngine {
	// Check for recursive types.
	if building != nil && building[info] {
		return nil
	}
	info.encInit.Lock()
	defer info.encInit.Unlock()
	enc, ok := info.encoder.Load().(*encEngine)
	if !ok {
		if building == nil {
			building = make(map[*typeInfo]bool)
		}
		building[info] = true
		enc = compileEnc(ut, building)
		info.encoder.Store(enc)
	}
	return enc
688 689
}

690
func (enc *Encoder) encode(b *encBuffer, value reflect.Value, ut *userTypeInfo) {
691
	defer catchError(&enc.err)
692
	engine := getEncEngine(ut, nil)
693
	indir := ut.indir
694
	if ut.externalEnc != 0 {
695 696 697
		indir = int(ut.encIndir)
	}
	for i := 0; i < indir; i++ {
698 699
		value = reflect.Indirect(value)
	}
700
	if ut.externalEnc == 0 && value.Type().Kind() == reflect.Struct {
701
		enc.encodeStruct(b, engine, value)
702
	} else {
703
		enc.encodeSingle(b, engine, value)
704 705
	}
}