encode.go 20 KB

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