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