encode.go 15.7 KB
Newer Older
Rob Pike's avatar
Rob Pike committed
1 2 3 4 5 6 7
// 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.

package gob

import (
8 9 10 11 12 13
	"bytes"
	"io"
	"math"
	"os"
	"reflect"
	"unsafe"
Rob Pike's avatar
Rob Pike committed
14 15
)

16 17
const uint64Size = unsafe.Sizeof(uint64(0))

18
// The global execution state of an instance of the encoder.
Rob Pike's avatar
Rob Pike committed
19 20 21
// 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.
22
type encoderState struct {
Rob Pike's avatar
Rob Pike committed
23
	enc      *Encoder
24
	b        *bytes.Buffer
25
	sendZero bool                 // encoding an array element or map key/value pair; send zero values
26 27
	fieldnum int                  // the last field number written.
	buf      [1 + uint64Size]byte // buffer used by the encoder; here to avoid allocation.
28 29
}

Rob Pike's avatar
Rob Pike committed
30 31
func newEncoderState(enc *Encoder, b *bytes.Buffer) *encoderState {
	return &encoderState{enc: enc, b: b}
32 33
}

34 35 36 37
// 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.
Rob Pike's avatar
Rob Pike committed
38

Rob Pike's avatar
Rob Pike committed
39
// encodeUint writes an encoded unsigned integer to state.b.
40
func (state *encoderState) encodeUint(x uint64) {
41
	if x <= 0x7F {
Rob Pike's avatar
Rob Pike committed
42 43 44 45
		err := state.b.WriteByte(uint8(x))
		if err != nil {
			error(err)
		}
46
		return
47
	}
48 49
	var n, m int
	m = uint64Size
50
	for n = 1; x > 0; n++ {
51 52 53
		state.buf[m] = uint8(x & 0xFF)
		x >>= 8
		m--
Rob Pike's avatar
Rob Pike committed
54
	}
55
	state.buf[m] = uint8(-(n - 1))
Rob Pike's avatar
Rob Pike committed
56 57 58 59
	n, err := state.b.Write(state.buf[m : uint64Size+1])
	if err != nil {
		error(err)
	}
Rob Pike's avatar
Rob Pike committed
60 61
}

62
// encodeInt writes an encoded signed integer to state.w.
Rob Pike's avatar
Rob Pike committed
63 64
// The low bit of the encoding says whether to bit complement the (other bits of the)
// uint to recover the int.
65
func (state *encoderState) encodeInt(i int64) {
66
	var x uint64
Rob Pike's avatar
Rob Pike committed
67
	if i < 0 {
68
		x = uint64(^i<<1) | 1
Rob Pike's avatar
Rob Pike committed
69
	} else {
70
		x = uint64(i << 1)
Rob Pike's avatar
Rob Pike committed
71
	}
72
	state.encodeUint(uint64(x))
Rob Pike's avatar
Rob Pike committed
73 74
}

75
type encOp func(i *encInstr, state *encoderState, p unsafe.Pointer)
76

Rob Pike's avatar
Rob Pike committed
77 78
// The 'instructions' of the encoding machine
type encInstr struct {
79 80 81 82
	op     encOp
	field  int     // field number
	indir  int     // how many pointer indirections to reach the value in the struct
	offset uintptr // offset in the structure of the field to encode
Rob Pike's avatar
Rob Pike committed
83 84
}

85 86
// Emit a field number and update the state to record its value for delta encoding.
// If the instruction pointer is nil, do nothing
87
func (state *encoderState) update(instr *encInstr) {
88
	if instr != nil {
89
		state.encodeUint(uint64(instr.field - state.fieldnum))
90
		state.fieldnum = instr.field
91 92 93
	}
}

94 95 96 97 98 99
// Each encoder is responsible for handling any indirections associated
// with the data structure.  If any pointer so reached is nil, no bytes are written.
// If the data item is zero, no bytes are written.
// Otherwise, the output (for a scalar) is the field number, as an encoded integer,
// followed by the field data in its appropriate format.

Rob Pike's avatar
Rob Pike committed
100 101
func encIndirect(p unsafe.Pointer, indir int) unsafe.Pointer {
	for ; indir > 0; indir-- {
102
		p = *(*unsafe.Pointer)(p)
Rob Pike's avatar
Rob Pike committed
103
		if p == nil {
104
			return unsafe.Pointer(nil)
Rob Pike's avatar
Rob Pike committed
105 106
		}
	}
107
	return p
Rob Pike's avatar
Rob Pike committed
108 109
}

110
func encBool(i *encInstr, state *encoderState, p unsafe.Pointer) {
111
	b := *(*bool)(p)
112
	if b || state.sendZero {
113
		state.update(i)
114
		if b {
115
			state.encodeUint(1)
116
		} else {
117
			state.encodeUint(0)
118
		}
Rob Pike's avatar
Rob Pike committed
119 120 121
	}
}

122
func encInt(i *encInstr, state *encoderState, p unsafe.Pointer) {
123
	v := int64(*(*int)(p))
124
	if v != 0 || state.sendZero {
125
		state.update(i)
126
		state.encodeInt(v)
Rob Pike's avatar
Rob Pike committed
127 128 129
	}
}

130
func encUint(i *encInstr, state *encoderState, p unsafe.Pointer) {
131
	v := uint64(*(*uint)(p))
132
	if v != 0 || state.sendZero {
133
		state.update(i)
134
		state.encodeUint(v)
Rob Pike's avatar
Rob Pike committed
135 136 137
	}
}

138
func encInt8(i *encInstr, state *encoderState, p unsafe.Pointer) {
139
	v := int64(*(*int8)(p))
140
	if v != 0 || state.sendZero {
141
		state.update(i)
142
		state.encodeInt(v)
Rob Pike's avatar
Rob Pike committed
143 144 145
	}
}

146
func encUint8(i *encInstr, state *encoderState, p unsafe.Pointer) {
147
	v := uint64(*(*uint8)(p))
148
	if v != 0 || state.sendZero {
149
		state.update(i)
150
		state.encodeUint(v)
Rob Pike's avatar
Rob Pike committed
151 152 153
	}
}

154
func encInt16(i *encInstr, state *encoderState, p unsafe.Pointer) {
155
	v := int64(*(*int16)(p))
156
	if v != 0 || state.sendZero {
157
		state.update(i)
158
		state.encodeInt(v)
Rob Pike's avatar
Rob Pike committed
159 160 161
	}
}

162
func encUint16(i *encInstr, state *encoderState, p unsafe.Pointer) {
163
	v := uint64(*(*uint16)(p))
164
	if v != 0 || state.sendZero {
165
		state.update(i)
166
		state.encodeUint(v)
Rob Pike's avatar
Rob Pike committed
167 168 169
	}
}

170
func encInt32(i *encInstr, state *encoderState, p unsafe.Pointer) {
171
	v := int64(*(*int32)(p))
172
	if v != 0 || state.sendZero {
173
		state.update(i)
174
		state.encodeInt(v)
Rob Pike's avatar
Rob Pike committed
175 176 177
	}
}

178
func encUint32(i *encInstr, state *encoderState, p unsafe.Pointer) {
179
	v := uint64(*(*uint32)(p))
180
	if v != 0 || state.sendZero {
181
		state.update(i)
182
		state.encodeUint(v)
Rob Pike's avatar
Rob Pike committed
183 184 185
	}
}

186
func encInt64(i *encInstr, state *encoderState, p unsafe.Pointer) {
187
	v := *(*int64)(p)
188
	if v != 0 || state.sendZero {
189
		state.update(i)
190
		state.encodeInt(v)
Rob Pike's avatar
Rob Pike committed
191 192 193
	}
}

194
func encUint64(i *encInstr, state *encoderState, p unsafe.Pointer) {
195
	v := *(*uint64)(p)
196
	if v != 0 || state.sendZero {
197
		state.update(i)
198
		state.encodeUint(v)
Rob Pike's avatar
Rob Pike committed
199 200 201
	}
}

202
func encUintptr(i *encInstr, state *encoderState, p unsafe.Pointer) {
203
	v := uint64(*(*uintptr)(p))
204
	if v != 0 || state.sendZero {
205
		state.update(i)
206
		state.encodeUint(v)
207 208 209
	}
}

Rob Pike's avatar
Rob Pike committed
210 211 212 213 214 215
// 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(f float64) uint64 {
216 217
	u := math.Float64bits(f)
	var v uint64
Rob Pike's avatar
Rob Pike committed
218
	for i := 0; i < 8; i++ {
219 220 221
		v <<= 8
		v |= u & 0xFF
		u >>= 8
Rob Pike's avatar
Rob Pike committed
222
	}
223
	return v
Rob Pike's avatar
Rob Pike committed
224 225
}

226
func encFloat32(i *encInstr, state *encoderState, p unsafe.Pointer) {
227
	f := *(*float32)(p)
228
	if f != 0 || state.sendZero {
229 230
		v := floatBits(float64(f))
		state.update(i)
231
		state.encodeUint(v)
Rob Pike's avatar
Rob Pike committed
232 233 234
	}
}

235
func encFloat64(i *encInstr, state *encoderState, p unsafe.Pointer) {
236
	f := *(*float64)(p)
237
	if f != 0 || state.sendZero {
238 239
		state.update(i)
		v := floatBits(f)
240
		state.encodeUint(v)
Rob Pike's avatar
Rob Pike committed
241 242
	}
}
Rob Pike's avatar
Rob Pike committed
243

244 245 246
// Complex numbers are just a pair of floating-point numbers, real part first.
func encComplex64(i *encInstr, state *encoderState, p unsafe.Pointer) {
	c := *(*complex64)(p)
247
	if c != 0+0i || state.sendZero {
248 249 250
		rpart := floatBits(float64(real(c)))
		ipart := floatBits(float64(imag(c)))
		state.update(i)
251 252
		state.encodeUint(rpart)
		state.encodeUint(ipart)
253 254 255 256 257
	}
}

func encComplex128(i *encInstr, state *encoderState, p unsafe.Pointer) {
	c := *(*complex128)(p)
258
	if c != 0+0i || state.sendZero {
259 260 261
		rpart := floatBits(real(c))
		ipart := floatBits(imag(c))
		state.update(i)
262 263
		state.encodeUint(rpart)
		state.encodeUint(ipart)
264 265 266
	}
}

267
// Byte arrays are encoded as an unsigned count followed by the raw bytes.
268
func encUint8Array(i *encInstr, state *encoderState, p unsafe.Pointer) {
269
	b := *(*[]byte)(p)
270
	if len(b) > 0 || state.sendZero {
271
		state.update(i)
272
		state.encodeUint(uint64(len(b)))
273
		state.b.Write(b)
274 275 276 277
	}
}

// Strings are encoded as an unsigned count followed by the raw bytes.
278
func encString(i *encInstr, state *encoderState, p unsafe.Pointer) {
279
	s := *(*string)(p)
280
	if len(s) > 0 || state.sendZero {
281
		state.update(i)
282
		state.encodeUint(uint64(len(s)))
283
		io.WriteString(state.b, s)
284 285 286
	}
}

Rob Pike's avatar
Rob Pike committed
287
// The end of a struct is marked by a delta field number of 0.
288
func encStructTerminator(i *encInstr, state *encoderState, p unsafe.Pointer) {
289
	state.encodeUint(0)
Rob Pike's avatar
Rob Pike committed
290 291 292 293 294 295 296
}

// Execution engine

// The encoder engine is 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 {
297
	instr []encInstr
Rob Pike's avatar
Rob Pike committed
298 299
}

300 301
const singletonField = 0

Rob Pike's avatar
Rob Pike committed
302 303
func (enc *Encoder) encodeSingle(b *bytes.Buffer, engine *encEngine, basep uintptr) {
	state := newEncoderState(enc, b)
304 305 306 307 308 309 310 311
	state.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.
	state.sendZero = true
	instr := &engine.instr[singletonField]
	p := unsafe.Pointer(basep) // offset will be zero
	if instr.indir > 0 {
		if p = encIndirect(p, instr.indir); p == nil {
Rob Pike's avatar
Rob Pike committed
312
			return
313 314 315 316 317
		}
	}
	instr.op(instr, state, p)
}

Rob Pike's avatar
Rob Pike committed
318 319
func (enc *Encoder) encodeStruct(b *bytes.Buffer, engine *encEngine, basep uintptr) {
	state := newEncoderState(enc, b)
320
	state.fieldnum = -1
321
	for i := 0; i < len(engine.instr); i++ {
322 323
		instr := &engine.instr[i]
		p := unsafe.Pointer(basep + instr.offset)
324 325
		if instr.indir > 0 {
			if p = encIndirect(p, instr.indir); p == nil {
326
				continue
327 328
			}
		}
329
		instr.op(instr, state, p)
330 331 332
	}
}

Rob Pike's avatar
Rob Pike committed
333 334
func (enc *Encoder) encodeArray(b *bytes.Buffer, p uintptr, op encOp, elemWid uintptr, elemIndir int, length int) {
	state := newEncoderState(enc, b)
335
	state.fieldnum = -1
336
	state.sendZero = true
337
	state.encodeUint(uint64(length))
Rob Pike's avatar
Rob Pike committed
338
	for i := 0; i < length; i++ {
339 340
		elemp := p
		up := unsafe.Pointer(elemp)
Rob Pike's avatar
Rob Pike committed
341 342
		if elemIndir > 0 {
			if up = encIndirect(up, elemIndir); up == nil {
Rob Pike's avatar
Rob Pike committed
343
				errorf("gob: encodeArray: nil element")
Rob Pike's avatar
Rob Pike committed
344
			}
345
			elemp = uintptr(up)
Rob Pike's avatar
Rob Pike committed
346
		}
347 348
		op(nil, state, unsafe.Pointer(elemp))
		p += uintptr(elemWid)
349 350 351
	}
}

Rob Pike's avatar
Rob Pike committed
352 353 354 355 356
func encodeReflectValue(state *encoderState, v reflect.Value, op encOp, indir int) {
	for i := 0; i < indir && v != nil; i++ {
		v = reflect.Indirect(v)
	}
	if v == nil {
Rob Pike's avatar
Rob Pike committed
357
		errorf("gob: encodeReflectValue: nil element")
Rob Pike's avatar
Rob Pike committed
358 359 360 361
	}
	op(nil, state, unsafe.Pointer(v.Addr()))
}

Rob Pike's avatar
Rob Pike committed
362 363
func (enc *Encoder) encodeMap(b *bytes.Buffer, mv *reflect.MapValue, keyOp, elemOp encOp, keyIndir, elemIndir int) {
	state := newEncoderState(enc, b)
Rob Pike's avatar
Rob Pike committed
364
	state.fieldnum = -1
365
	state.sendZero = true
Rob Pike's avatar
Rob Pike committed
366
	keys := mv.Keys()
367
	state.encodeUint(uint64(len(keys)))
Rob Pike's avatar
Rob Pike committed
368 369 370 371 372 373
	for _, key := range keys {
		encodeReflectValue(state, key, keyOp, keyIndir)
		encodeReflectValue(state, mv.Elem(key), elemOp, elemIndir)
	}
}

374 375 376 377
// 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.
Rob Pike's avatar
Rob Pike committed
378
func (enc *Encoder) encodeInterface(b *bytes.Buffer, iv *reflect.InterfaceValue) {
Rob Pike's avatar
Rob Pike committed
379
	state := newEncoderState(enc, b)
380 381 382
	state.fieldnum = -1
	state.sendZero = true
	if iv.IsNil() {
383
		state.encodeUint(0)
Rob Pike's avatar
Rob Pike committed
384
		return
385 386
	}

387
	typ, _ := indirect(iv.Elem().Type())
388 389
	name, ok := concreteTypeToName[typ]
	if !ok {
Rob Pike's avatar
Rob Pike committed
390
		errorf("gob: type not registered for interface: %s", typ)
391 392
	}
	// Send the name.
393
	state.encodeUint(uint64(len(name)))
Rob Pike's avatar
Rob Pike committed
394 395 396
	_, err := io.WriteString(state.b, name)
	if err != nil {
		error(err)
397 398 399
	}
	// Send (and maybe first define) the type id.
	enc.sendTypeDescriptor(typ)
Rob Pike's avatar
Rob Pike committed
400 401 402 403 404 405
	// Encode the value into a new buffer.
	data := new(bytes.Buffer)
	err = enc.encode(data, iv.Elem())
	if err != nil {
		error(err)
	}
406
	state.encodeUint(uint64(data.Len()))
Rob Pike's avatar
Rob Pike committed
407
	_, err = state.b.Write(data.Bytes())
Rob Pike's avatar
Rob Pike committed
408 409 410
	if err != nil {
		error(err)
	}
411 412
}

413
var encOpMap = []encOp{
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
	reflect.Bool:       encBool,
	reflect.Int:        encInt,
	reflect.Int8:       encInt8,
	reflect.Int16:      encInt16,
	reflect.Int32:      encInt32,
	reflect.Int64:      encInt64,
	reflect.Uint:       encUint,
	reflect.Uint8:      encUint8,
	reflect.Uint16:     encUint16,
	reflect.Uint32:     encUint32,
	reflect.Uint64:     encUint64,
	reflect.Uintptr:    encUintptr,
	reflect.Float32:    encFloat32,
	reflect.Float64:    encFloat64,
	reflect.Complex64:  encComplex64,
	reflect.Complex128: encComplex128,
	reflect.String:     encString,
431 432
}

433 434
// Return the encoding op for the base type under rt and
// the indirection count to reach it.
Rob Pike's avatar
Rob Pike committed
435
func (enc *Encoder) encOpFor(rt reflect.Type) (encOp, int) {
436
	typ, indir := indirect(rt)
437 438 439 440 441 442
	var op encOp
	k := typ.Kind()
	if int(k) < len(encOpMap) {
		op = encOpMap[k]
	}
	if op == nil {
443
		// Special cases
Russ Cox's avatar
Russ Cox committed
444 445
		switch t := typ.(type) {
		case *reflect.SliceType:
446
			if t.Elem().Kind() == reflect.Uint8 {
447 448
				op = encUint8Array
				break
449
			}
Russ Cox's avatar
Russ Cox committed
450
			// Slices have a header; we decode it to find the underlying array.
Rob Pike's avatar
Rob Pike committed
451
			elemOp, indir := enc.encOpFor(t.Elem())
452
			op = func(i *encInstr, state *encoderState, p unsafe.Pointer) {
453
				slice := (*reflect.SliceHeader)(p)
454
				if !state.sendZero && slice.Len == 0 {
455
					return
Russ Cox's avatar
Russ Cox committed
456
				}
457
				state.update(i)
Rob Pike's avatar
Rob Pike committed
458
				state.enc.encodeArray(state.b, slice.Data, elemOp, t.Elem().Size(), indir, int(slice.Len))
459
			}
Russ Cox's avatar
Russ Cox committed
460 461
		case *reflect.ArrayType:
			// True arrays have size in the type.
Rob Pike's avatar
Rob Pike committed
462
			elemOp, indir := enc.encOpFor(t.Elem())
463
			op = func(i *encInstr, state *encoderState, p unsafe.Pointer) {
464
				state.update(i)
Rob Pike's avatar
Rob Pike committed
465
				state.enc.encodeArray(state.b, uintptr(p), elemOp, t.Elem().Size(), indir, t.Len())
Rob Pike's avatar
Rob Pike committed
466 467
			}
		case *reflect.MapType:
Rob Pike's avatar
Rob Pike committed
468 469
			keyOp, keyIndir := enc.encOpFor(t.Key())
			elemOp, elemIndir := enc.encOpFor(t.Elem())
Rob Pike's avatar
Rob Pike committed
470
			op = func(i *encInstr, state *encoderState, p unsafe.Pointer) {
471 472 473 474 475
				// Maps cannot be accessed by moving addresses around the way
				// that slices etc. can.  We must recover a full reflection value for
				// the iteration.
				v := reflect.NewValue(unsafe.Unreflect(t, unsafe.Pointer((p))))
				mv := reflect.Indirect(v).(*reflect.MapValue)
476
				if !state.sendZero && mv.Len() == 0 {
477 478
					return
				}
Rob Pike's avatar
Rob Pike committed
479
				state.update(i)
Rob Pike's avatar
Rob Pike committed
480
				state.enc.encodeMap(state.b, mv, keyOp, elemOp, keyIndir, elemIndir)
481
			}
Russ Cox's avatar
Russ Cox committed
482
		case *reflect.StructType:
483
			// Generate a closure that calls out to the engine for the nested type.
Rob Pike's avatar
Rob Pike committed
484
			enc.getEncEngine(typ)
485
			info := mustGetTypeInfo(typ)
486
			op = func(i *encInstr, state *encoderState, p unsafe.Pointer) {
487
				state.update(i)
488
				// indirect through info to delay evaluation for recursive structs
Rob Pike's avatar
Rob Pike committed
489
				state.enc.encodeStruct(state.b, info.encoder, uintptr(p))
490
			}
491 492 493 494 495 496 497 498 499 500
		case *reflect.InterfaceType:
			op = func(i *encInstr, state *encoderState, p unsafe.Pointer) {
				// Interfaces transmit the name and contents of the concrete
				// value they contain.
				v := reflect.NewValue(unsafe.Unreflect(t, unsafe.Pointer((p))))
				iv := reflect.Indirect(v).(*reflect.InterfaceValue)
				if !state.sendZero && (iv == nil || iv.IsNil()) {
					return
				}
				state.update(i)
Rob Pike's avatar
Rob Pike committed
501
				state.enc.encodeInterface(state.b, iv)
502
			}
503
		}
504 505
	}
	if op == nil {
Rob Pike's avatar
Rob Pike committed
506
		errorf("gob enc: can't happen: encode type %s", rt.String())
507
	}
Rob Pike's avatar
Rob Pike committed
508
	return op, indir
Rob Pike's avatar
Rob Pike committed
509 510
}

511
// The local Type was compiled from the actual value, so we know it's compatible.
Rob Pike's avatar
Rob Pike committed
512
func (enc *Encoder) compileEnc(rt reflect.Type) *encEngine {
513
	srt, isStruct := rt.(*reflect.StructType)
514
	engine := new(encEngine)
515
	if isStruct {
516 517
		for fieldNum := 0; fieldNum < srt.NumField(); fieldNum++ {
			f := srt.Field(fieldNum)
518
			if !isExported(f.Name) {
519
				continue
520
			}
521 522 523 524 525
			op, indir := enc.encOpFor(f.Type)
			engine.instr = append(engine.instr, encInstr{op, fieldNum, indir, uintptr(f.Offset)})
		}
		if srt.NumField() > 0 && len(engine.instr) == 0 {
			errorf("type %s has no exported fields", rt)
526
		}
527
		engine.instr = append(engine.instr, encInstr{encStructTerminator, 0, 0, 0})
528 529
	} else {
		engine.instr = make([]encInstr, 1)
Rob Pike's avatar
Rob Pike committed
530
		op, indir := enc.encOpFor(rt)
531
		engine.instr[0] = encInstr{op, singletonField, indir, 0} // offset is zero
Rob Pike's avatar
Rob Pike committed
532
	}
Rob Pike's avatar
Rob Pike committed
533
	return engine
Rob Pike's avatar
Rob Pike committed
534 535
}

536 537
// typeLock must be held (or we're in initialization and guaranteed single-threaded).
// The reflection type must have all its indirections processed out.
Rob Pike's avatar
Rob Pike committed
538 539 540 541
func (enc *Encoder) getEncEngine(rt reflect.Type) *encEngine {
	info, err1 := getTypeInfo(rt)
	if err1 != nil {
		error(err1)
Rob Pike's avatar
Rob Pike committed
542
	}
543 544
	if info.encoder == nil {
		// mark this engine as underway before compiling to handle recursive types.
545
		info.encoder = new(encEngine)
Rob Pike's avatar
Rob Pike committed
546
		info.encoder = enc.compileEnc(rt)
Rob Pike's avatar
Rob Pike committed
547
	}
Rob Pike's avatar
Rob Pike committed
548
	return info.encoder
Rob Pike's avatar
Rob Pike committed
549 550
}

Rob Pike's avatar
Rob Pike committed
551 552 553 554 555 556 557 558 559
// Put this in a function so we can hold the lock only while compiling, not when encoding.
func (enc *Encoder) lockAndGetEncEngine(rt reflect.Type) *encEngine {
	typeLock.Lock()
	defer typeLock.Unlock()
	return enc.getEncEngine(rt)
}

func (enc *Encoder) encode(b *bytes.Buffer, value reflect.Value) (err os.Error) {
	defer catchError(&err)
Rob Pike's avatar
Rob Pike committed
560
	// Dereference down to the underlying object.
561
	rt, indir := indirect(value.Type())
Rob Pike's avatar
Rob Pike committed
562
	for i := 0; i < indir; i++ {
563
		value = reflect.Indirect(value)
Rob Pike's avatar
Rob Pike committed
564
	}
Rob Pike's avatar
Rob Pike committed
565
	engine := enc.lockAndGetEncEngine(rt)
566
	if value.Type().Kind() == reflect.Struct {
Rob Pike's avatar
Rob Pike committed
567
		enc.encodeStruct(b, engine, value.Addr())
Rob Pike's avatar
Rob Pike committed
568
	} else {
Rob Pike's avatar
Rob Pike committed
569
		enc.encodeSingle(b, engine, value.Addr())
570
	}
Rob Pike's avatar
Rob Pike committed
571
	return nil
Rob Pike's avatar
Rob Pike committed
572
}