encode.go 20 KB

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