You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

737 lines
18 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. package binary
  2. import (
  3. "encoding/hex"
  4. "encoding/json"
  5. "errors"
  6. "io"
  7. "reflect"
  8. "sync"
  9. "time"
  10. . "github.com/tendermint/tendermint/common"
  11. )
  12. type TypeInfo struct {
  13. Type reflect.Type // The type
  14. // Custom encoder/decoder
  15. // NOTE: Not used.
  16. BinaryEncoder Encoder
  17. BinaryDecoder Decoder
  18. // If Type is kind reflect.Interface
  19. ConcreteTypes map[byte]reflect.Type
  20. // If Type is concrete
  21. HasTypeByte bool
  22. TypeByte byte
  23. // If Type is kind reflect.Struct
  24. Fields []StructFieldInfo
  25. }
  26. type StructFieldInfo struct {
  27. Index int // Struct field index
  28. JSONName string // Corresponding JSON field name. (override with `json=""`)
  29. Type reflect.Type // Struct field type
  30. }
  31. func (info StructFieldInfo) unpack() (int, string, reflect.Type) {
  32. return info.Index, info.JSONName, info.Type
  33. }
  34. // e.g. If o is struct{Foo}{}, return is the Foo interface type.
  35. func GetTypeFromStructDeclaration(o interface{}) reflect.Type {
  36. rt := reflect.TypeOf(o)
  37. if rt.NumField() != 1 {
  38. panic("Unexpected number of fields in struct-wrapped declaration of type")
  39. }
  40. return rt.Field(0).Type
  41. }
  42. // If o implements HasTypeByte, returns (true, typeByte)
  43. func GetTypeByteFromStruct(o interface{}) (hasTypeByte bool, typeByte byte) {
  44. if _, ok := o.(HasTypeByte); ok {
  45. return true, o.(HasTypeByte).TypeByte()
  46. } else {
  47. return false, byte(0x00)
  48. }
  49. }
  50. // Predeclaration of common types
  51. var (
  52. timeType = GetTypeFromStructDeclaration(struct{ time.Time }{})
  53. )
  54. const (
  55. rfc2822 = "Mon Jan 02 15:04:05 -0700 2006"
  56. )
  57. // If a type implements TypeByte, the byte is included
  58. // as the first byte for encoding and decoding.
  59. // This is primarily used to encode interfaces types.
  60. // The interface should be declared with RegisterInterface()
  61. type HasTypeByte interface {
  62. TypeByte() byte
  63. }
  64. // NOTE: do not access typeInfos directly, but call GetTypeInfo()
  65. var typeInfosMtx sync.Mutex
  66. var typeInfos = map[reflect.Type]*TypeInfo{}
  67. func GetTypeInfo(rt reflect.Type) *TypeInfo {
  68. typeInfosMtx.Lock()
  69. defer typeInfosMtx.Unlock()
  70. info := typeInfos[rt]
  71. if info == nil {
  72. info = &TypeInfo{Type: rt}
  73. RegisterType(info)
  74. }
  75. return info
  76. }
  77. // For use with the RegisterInterface declaration
  78. type ConcreteType struct {
  79. O interface{}
  80. }
  81. // Must use this to register an interface to properly decode the
  82. // underlying concrete type.
  83. func RegisterInterface(o interface{}, args ...interface{}) *TypeInfo {
  84. it := GetTypeFromStructDeclaration(o)
  85. if it.Kind() != reflect.Interface {
  86. panic("RegisterInterface expects an interface")
  87. }
  88. concreteTypes := make(map[byte]reflect.Type, 0)
  89. for _, arg := range args {
  90. switch arg.(type) {
  91. case ConcreteType:
  92. concreteTypeInfo := arg.(ConcreteType)
  93. concreteType := reflect.TypeOf(concreteTypeInfo.O)
  94. hasTypeByte, typeByte := GetTypeByteFromStruct(concreteTypeInfo.O)
  95. //fmt.Println(Fmt("HasTypeByte: %v typeByte: %X type: %X", hasTypeByte, typeByte, concreteType))
  96. if !hasTypeByte {
  97. panic(Fmt("Expected concrete type %v to implement HasTypeByte", concreteType))
  98. }
  99. if concreteTypes[typeByte] != nil {
  100. panic(Fmt("Duplicate TypeByte for type %v and %v", concreteType, concreteTypes[typeByte]))
  101. }
  102. concreteTypes[typeByte] = concreteType
  103. default:
  104. panic(Fmt("Unexpected argument type %v", reflect.TypeOf(arg)))
  105. }
  106. }
  107. typeInfo := &TypeInfo{
  108. Type: it,
  109. ConcreteTypes: concreteTypes,
  110. }
  111. typeInfos[it] = typeInfo
  112. return typeInfo
  113. }
  114. // Registers and possibly modifies the TypeInfo.
  115. // NOTE: not goroutine safe, so only call upon program init.
  116. func RegisterType(info *TypeInfo) *TypeInfo {
  117. // Also register the dereferenced struct if info.Type is a pointer.
  118. // Or, if info.Type is not a pointer, register the pointer.
  119. var rt, ptrRt reflect.Type
  120. if info.Type.Kind() == reflect.Ptr {
  121. rt, ptrRt = info.Type.Elem(), info.Type
  122. } else {
  123. rt, ptrRt = info.Type, reflect.PtrTo(info.Type)
  124. }
  125. // Register the type info
  126. typeInfos[rt] = info
  127. typeInfos[ptrRt] = info
  128. // See if the type implements HasTypeByte
  129. if rt.Kind() != reflect.Interface && rt.Implements(reflect.TypeOf((*HasTypeByte)(nil)).Elem()) {
  130. zero := reflect.Zero(rt)
  131. typeByte := zero.Interface().(HasTypeByte).TypeByte()
  132. if info.HasTypeByte && info.TypeByte != typeByte {
  133. panic(Fmt("Type %v expected TypeByte of %X", rt, typeByte))
  134. } else {
  135. info.HasTypeByte = true
  136. info.TypeByte = typeByte
  137. }
  138. } else if ptrRt.Implements(reflect.TypeOf((*HasTypeByte)(nil)).Elem()) {
  139. zero := reflect.Zero(ptrRt)
  140. typeByte := zero.Interface().(HasTypeByte).TypeByte()
  141. if info.HasTypeByte && info.TypeByte != typeByte {
  142. panic(Fmt("Type %v expected TypeByte of %X", ptrRt, typeByte))
  143. } else {
  144. info.HasTypeByte = true
  145. info.TypeByte = typeByte
  146. }
  147. }
  148. // If struct, register field name options
  149. if rt.Kind() == reflect.Struct {
  150. numFields := rt.NumField()
  151. structFields := []StructFieldInfo{}
  152. for i := 0; i < numFields; i++ {
  153. field := rt.Field(i)
  154. if field.PkgPath != "" {
  155. continue
  156. }
  157. jsonName := field.Tag.Get("json")
  158. if jsonName == "" {
  159. jsonName = field.Name
  160. }
  161. structFields = append(structFields, StructFieldInfo{
  162. Index: i,
  163. JSONName: jsonName,
  164. Type: field.Type,
  165. })
  166. }
  167. info.Fields = structFields
  168. }
  169. return info
  170. }
  171. func readReflect(rv reflect.Value, rt reflect.Type, r io.Reader, n *int64, err *error) {
  172. log.Debug("Read reflect", "type", rt)
  173. // Get typeInfo
  174. typeInfo := GetTypeInfo(rt)
  175. // Custom decoder
  176. if typeInfo.BinaryDecoder != nil {
  177. decoded := typeInfo.BinaryDecoder(r, n, err)
  178. rv.Set(reflect.ValueOf(decoded))
  179. return
  180. }
  181. // Create a new struct if rv is nil pointer.
  182. if rt.Kind() == reflect.Ptr && rv.IsNil() {
  183. newRv := reflect.New(rt.Elem())
  184. rv.Set(newRv)
  185. rv = newRv
  186. }
  187. // Dereference pointer
  188. // Still addressable, thus settable!
  189. if rv.Kind() == reflect.Ptr {
  190. rv, rt = rv.Elem(), rt.Elem()
  191. }
  192. // Read TypeByte prefix
  193. if typeInfo.HasTypeByte {
  194. typeByte := ReadByte(r, n, err)
  195. log.Debug("Read typebyte", "typeByte", typeByte)
  196. if typeByte != typeInfo.TypeByte {
  197. *err = errors.New(Fmt("Expected TypeByte of %X but got %X", typeInfo.TypeByte, typeByte))
  198. return
  199. }
  200. }
  201. switch rt.Kind() {
  202. case reflect.Interface:
  203. typeByte := ReadByte(r, n, err)
  204. if *err != nil {
  205. return
  206. }
  207. concreteType, ok := typeInfo.ConcreteTypes[typeByte]
  208. if !ok {
  209. panic(Fmt("TypeByte %X not registered for interface %v", typeByte, rt))
  210. }
  211. newRv := reflect.New(concreteType)
  212. readReflect(newRv.Elem(), concreteType, NewPrefixedReader([]byte{typeByte}, r), n, err)
  213. rv.Set(newRv.Elem())
  214. case reflect.Slice:
  215. elemRt := rt.Elem()
  216. if elemRt.Kind() == reflect.Uint8 {
  217. // Special case: Byteslices
  218. byteslice := ReadByteSlice(r, n, err)
  219. log.Debug("Read byteslice", "bytes", byteslice)
  220. rv.Set(reflect.ValueOf(byteslice))
  221. } else {
  222. // Read length
  223. length := int(ReadUvarint(r, n, err))
  224. log.Debug(Fmt("Read length: %v", length))
  225. sliceRv := reflect.MakeSlice(rt, length, length)
  226. // Read elems
  227. for i := 0; i < length; i++ {
  228. elemRv := sliceRv.Index(i)
  229. readReflect(elemRv, elemRt, r, n, err)
  230. }
  231. rv.Set(sliceRv)
  232. }
  233. case reflect.Struct:
  234. if rt == timeType {
  235. // Special case: time.Time
  236. t := ReadTime(r, n, err)
  237. log.Debug(Fmt("Read time: %v", t))
  238. rv.Set(reflect.ValueOf(t))
  239. } else {
  240. numFields := rt.NumField()
  241. for i := 0; i < numFields; i++ {
  242. field := rt.Field(i)
  243. if field.PkgPath != "" {
  244. continue
  245. }
  246. fieldRv := rv.Field(i)
  247. readReflect(fieldRv, field.Type, r, n, err)
  248. }
  249. }
  250. case reflect.String:
  251. str := ReadString(r, n, err)
  252. log.Debug(Fmt("Read string: %v", str))
  253. rv.SetString(str)
  254. case reflect.Int64:
  255. num := ReadUint64(r, n, err)
  256. log.Debug(Fmt("Read num: %v", num))
  257. rv.SetInt(int64(num))
  258. case reflect.Int32:
  259. num := ReadUint32(r, n, err)
  260. log.Debug(Fmt("Read num: %v", num))
  261. rv.SetInt(int64(num))
  262. case reflect.Int16:
  263. num := ReadUint16(r, n, err)
  264. log.Debug(Fmt("Read num: %v", num))
  265. rv.SetInt(int64(num))
  266. case reflect.Int8:
  267. num := ReadUint8(r, n, err)
  268. log.Debug(Fmt("Read num: %v", num))
  269. rv.SetInt(int64(num))
  270. case reflect.Int:
  271. num := ReadUvarint(r, n, err)
  272. log.Debug(Fmt("Read num: %v", num))
  273. rv.SetInt(int64(num))
  274. case reflect.Uint64:
  275. num := ReadUint64(r, n, err)
  276. log.Debug(Fmt("Read num: %v", num))
  277. rv.SetUint(uint64(num))
  278. case reflect.Uint32:
  279. num := ReadUint32(r, n, err)
  280. log.Debug(Fmt("Read num: %v", num))
  281. rv.SetUint(uint64(num))
  282. case reflect.Uint16:
  283. num := ReadUint16(r, n, err)
  284. log.Debug(Fmt("Read num: %v", num))
  285. rv.SetUint(uint64(num))
  286. case reflect.Uint8:
  287. num := ReadUint8(r, n, err)
  288. log.Debug(Fmt("Read num: %v", num))
  289. rv.SetUint(uint64(num))
  290. case reflect.Uint:
  291. num := ReadUvarint(r, n, err)
  292. log.Debug(Fmt("Read num: %v", num))
  293. rv.SetUint(uint64(num))
  294. case reflect.Bool:
  295. num := ReadUint8(r, n, err)
  296. log.Debug(Fmt("Read bool: %v", num))
  297. rv.SetBool(num > 0)
  298. default:
  299. panic(Fmt("Unknown field type %v", rt.Kind()))
  300. }
  301. }
  302. func writeReflect(rv reflect.Value, rt reflect.Type, w io.Writer, n *int64, err *error) {
  303. // Get typeInfo
  304. typeInfo := GetTypeInfo(rt)
  305. // Custom encoder, say for an interface type rt.
  306. if typeInfo.BinaryEncoder != nil {
  307. typeInfo.BinaryEncoder(rv.Interface(), w, n, err)
  308. return
  309. }
  310. // Dereference interface
  311. if rt.Kind() == reflect.Interface {
  312. rv = rv.Elem()
  313. rt = rv.Type()
  314. // If interface type, get typeInfo of underlying type.
  315. typeInfo = GetTypeInfo(rt)
  316. }
  317. // Dereference pointer
  318. if rt.Kind() == reflect.Ptr {
  319. rt = rt.Elem()
  320. rv = rv.Elem()
  321. }
  322. // Write TypeByte prefix
  323. if typeInfo.HasTypeByte {
  324. WriteByte(typeInfo.TypeByte, w, n, err)
  325. }
  326. switch rt.Kind() {
  327. case reflect.Slice:
  328. elemRt := rt.Elem()
  329. if elemRt.Kind() == reflect.Uint8 {
  330. // Special case: Byteslices
  331. byteslice := rv.Bytes()
  332. WriteByteSlice(byteslice, w, n, err)
  333. } else {
  334. // Write length
  335. length := rv.Len()
  336. WriteUvarint(uint(length), w, n, err)
  337. // Write elems
  338. for i := 0; i < length; i++ {
  339. elemRv := rv.Index(i)
  340. writeReflect(elemRv, elemRt, w, n, err)
  341. }
  342. }
  343. case reflect.Struct:
  344. if rt == timeType {
  345. // Special case: time.Time
  346. WriteTime(rv.Interface().(time.Time), w, n, err)
  347. } else {
  348. numFields := rt.NumField()
  349. for i := 0; i < numFields; i++ {
  350. field := rt.Field(i)
  351. if field.PkgPath != "" {
  352. continue
  353. }
  354. fieldRv := rv.Field(i)
  355. writeReflect(fieldRv, field.Type, w, n, err)
  356. }
  357. }
  358. case reflect.String:
  359. WriteString(rv.String(), w, n, err)
  360. case reflect.Int64:
  361. WriteInt64(rv.Int(), w, n, err)
  362. case reflect.Int32:
  363. WriteInt32(int32(rv.Int()), w, n, err)
  364. case reflect.Int16:
  365. WriteInt16(int16(rv.Int()), w, n, err)
  366. case reflect.Int8:
  367. WriteInt8(int8(rv.Int()), w, n, err)
  368. case reflect.Int:
  369. WriteVarint(int(rv.Int()), w, n, err)
  370. case reflect.Uint64:
  371. WriteUint64(rv.Uint(), w, n, err)
  372. case reflect.Uint32:
  373. WriteUint32(uint32(rv.Uint()), w, n, err)
  374. case reflect.Uint16:
  375. WriteUint16(uint16(rv.Uint()), w, n, err)
  376. case reflect.Uint8:
  377. WriteUint8(uint8(rv.Uint()), w, n, err)
  378. case reflect.Uint:
  379. WriteUvarint(uint(rv.Uint()), w, n, err)
  380. case reflect.Bool:
  381. if rv.Bool() {
  382. WriteUint8(uint8(1), w, n, err)
  383. } else {
  384. WriteUint8(uint8(0), w, n, err)
  385. }
  386. default:
  387. panic(Fmt("Unknown field type %v", rt.Kind()))
  388. }
  389. }
  390. //-----------------------------------------------------------------------------
  391. func readTypeByteJSON(o interface{}) (typeByte byte, rest interface{}, err error) {
  392. oSlice, ok := o.([]interface{})
  393. if !ok {
  394. err = errors.New(Fmt("Expected type [TypeByte,?] but got type %v", reflect.TypeOf(o)))
  395. return
  396. }
  397. if len(oSlice) != 2 {
  398. err = errors.New(Fmt("Expected [TypeByte,?] len 2 but got len %v", len(oSlice)))
  399. return
  400. }
  401. typeByte_, ok := oSlice[0].(float64)
  402. typeByte = byte(typeByte_)
  403. rest = oSlice[1]
  404. return
  405. }
  406. func readReflectJSON(rv reflect.Value, rt reflect.Type, o interface{}, err *error) {
  407. log.Debug("Read reflect json", "type", rt)
  408. // Get typeInfo
  409. typeInfo := GetTypeInfo(rt)
  410. // Create a new struct if rv is nil pointer.
  411. if rt.Kind() == reflect.Ptr && rv.IsNil() {
  412. newRv := reflect.New(rt.Elem())
  413. rv.Set(newRv)
  414. rv = newRv
  415. }
  416. // Dereference pointer
  417. // Still addressable, thus settable!
  418. if rv.Kind() == reflect.Ptr {
  419. rv, rt = rv.Elem(), rt.Elem()
  420. }
  421. // Read TypeByte prefix
  422. if typeInfo.HasTypeByte {
  423. typeByte, rest, err_ := readTypeByteJSON(o)
  424. if err_ != nil {
  425. *err = err_
  426. return
  427. }
  428. if typeByte != typeInfo.TypeByte {
  429. *err = errors.New(Fmt("Expected TypeByte of %X but got %X", typeInfo.TypeByte, byte(typeByte)))
  430. return
  431. }
  432. o = rest
  433. }
  434. switch rt.Kind() {
  435. case reflect.Interface:
  436. typeByte, _, err_ := readTypeByteJSON(o)
  437. if err_ != nil {
  438. *err = err_
  439. return
  440. }
  441. concreteType, ok := typeInfo.ConcreteTypes[typeByte]
  442. if !ok {
  443. panic(Fmt("TypeByte %X not registered for interface %v", typeByte, rt))
  444. }
  445. newRv := reflect.New(concreteType)
  446. readReflectJSON(newRv.Elem(), concreteType, o, err)
  447. rv.Set(newRv.Elem())
  448. case reflect.Slice:
  449. elemRt := rt.Elem()
  450. if elemRt.Kind() == reflect.Uint8 {
  451. // Special case: Byteslices
  452. oString, ok := o.(string)
  453. if !ok {
  454. *err = errors.New(Fmt("Expected string but got type %v", reflect.TypeOf(o)))
  455. return
  456. }
  457. byteslice, err_ := hex.DecodeString(oString)
  458. if err_ != nil {
  459. *err = err_
  460. return
  461. }
  462. log.Debug("Read byteslice", "bytes", byteslice)
  463. rv.Set(reflect.ValueOf(byteslice))
  464. } else {
  465. // Read length
  466. oSlice, ok := o.([]interface{})
  467. if !ok {
  468. *err = errors.New(Fmt("Expected array but got type %v", reflect.TypeOf(o)))
  469. return
  470. }
  471. length := len(oSlice)
  472. log.Debug(Fmt("Read length: %v", length))
  473. sliceRv := reflect.MakeSlice(rt, length, length)
  474. // Read elems
  475. for i := 0; i < length; i++ {
  476. elemRv := sliceRv.Index(i)
  477. readReflectJSON(elemRv, elemRt, oSlice[i], err)
  478. }
  479. rv.Set(sliceRv)
  480. }
  481. case reflect.Struct:
  482. if rt == timeType {
  483. // Special case: time.Time
  484. str, ok := o.(string)
  485. if !ok {
  486. *err = errors.New(Fmt("Expected string but got type %v", reflect.TypeOf(o)))
  487. return
  488. }
  489. log.Debug(Fmt("Read time: %v", str))
  490. t, err_ := time.Parse(rfc2822, str)
  491. if err_ != nil {
  492. *err = err_
  493. return
  494. }
  495. rv.Set(reflect.ValueOf(t))
  496. } else {
  497. oMap, ok := o.(map[string]interface{})
  498. if !ok {
  499. *err = errors.New(Fmt("Expected map but got type %v", reflect.TypeOf(o)))
  500. return
  501. }
  502. // TODO: ensure that all fields are set?
  503. // TODO: disallow unknown oMap fields?
  504. for _, fieldInfo := range typeInfo.Fields {
  505. i, jsonName, fieldType := fieldInfo.unpack()
  506. value, ok := oMap[jsonName]
  507. if !ok {
  508. continue // Skip missing fields.
  509. }
  510. fieldRv := rv.Field(i)
  511. readReflectJSON(fieldRv, fieldType, value, err)
  512. }
  513. }
  514. case reflect.String:
  515. str, ok := o.(string)
  516. if !ok {
  517. *err = errors.New(Fmt("Expected string but got type %v", reflect.TypeOf(o)))
  518. return
  519. }
  520. log.Debug(Fmt("Read string: %v", str))
  521. rv.SetString(str)
  522. case reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8, reflect.Int:
  523. num, ok := o.(float64)
  524. if !ok {
  525. *err = errors.New(Fmt("Expected numeric but got type %v", reflect.TypeOf(o)))
  526. return
  527. }
  528. log.Debug(Fmt("Read num: %v", num))
  529. rv.SetInt(int64(num))
  530. case reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8, reflect.Uint:
  531. num, ok := o.(float64)
  532. if !ok {
  533. *err = errors.New(Fmt("Expected numeric but got type %v", reflect.TypeOf(o)))
  534. return
  535. }
  536. if num < 0 {
  537. *err = errors.New(Fmt("Expected unsigned numeric but got %v", num))
  538. return
  539. }
  540. log.Debug(Fmt("Read num: %v", num))
  541. rv.SetUint(uint64(num))
  542. case reflect.Bool:
  543. bl, ok := o.(bool)
  544. if !ok {
  545. *err = errors.New(Fmt("Expected boolean but got type %v", reflect.TypeOf(o)))
  546. return
  547. }
  548. log.Debug(Fmt("Read boolean: %v", bl))
  549. rv.SetBool(bl)
  550. default:
  551. panic(Fmt("Unknown field type %v", rt.Kind()))
  552. }
  553. }
  554. func writeReflectJSON(rv reflect.Value, rt reflect.Type, w io.Writer, n *int64, err *error) {
  555. // Get typeInfo
  556. typeInfo := GetTypeInfo(rt)
  557. // Dereference interface
  558. if rt.Kind() == reflect.Interface {
  559. rv = rv.Elem()
  560. rt = rv.Type()
  561. // If interface type, get typeInfo of underlying type.
  562. typeInfo = GetTypeInfo(rt)
  563. }
  564. // Dereference pointer
  565. if rt.Kind() == reflect.Ptr {
  566. rt = rt.Elem()
  567. rv = rv.Elem()
  568. }
  569. // Write TypeByte prefix
  570. if typeInfo.HasTypeByte {
  571. WriteTo([]byte(Fmt("[%v,", typeInfo.TypeByte)), w, n, err)
  572. }
  573. switch rt.Kind() {
  574. case reflect.Slice:
  575. elemRt := rt.Elem()
  576. if elemRt.Kind() == reflect.Uint8 {
  577. // Special case: Byteslices
  578. byteslice := rv.Bytes()
  579. WriteTo([]byte(Fmt("\"%X\"", byteslice)), w, n, err)
  580. //WriteByteSlice(byteslice, w, n, err)
  581. } else {
  582. WriteTo([]byte("["), w, n, err)
  583. // Write elems
  584. length := rv.Len()
  585. for i := 0; i < length; i++ {
  586. elemRv := rv.Index(i)
  587. writeReflectJSON(elemRv, elemRt, w, n, err)
  588. if i < length-1 {
  589. WriteTo([]byte(","), w, n, err)
  590. }
  591. }
  592. WriteTo([]byte("]"), w, n, err)
  593. }
  594. case reflect.Struct:
  595. if rt == timeType {
  596. // Special case: time.Time
  597. t := rv.Interface().(time.Time)
  598. str := t.Format(rfc2822)
  599. jsonBytes, err_ := json.Marshal(str)
  600. if err_ != nil {
  601. *err = err_
  602. return
  603. }
  604. WriteTo(jsonBytes, w, n, err)
  605. } else {
  606. WriteTo([]byte("{"), w, n, err)
  607. wroteField := false
  608. for _, fieldInfo := range typeInfo.Fields {
  609. i, jsonName, fieldType := fieldInfo.unpack()
  610. fieldRv := rv.Field(i)
  611. if wroteField {
  612. WriteTo([]byte(","), w, n, err)
  613. } else {
  614. wroteField = true
  615. }
  616. WriteTo([]byte(Fmt("\"%v\":", jsonName)), w, n, err)
  617. writeReflectJSON(fieldRv, fieldType, w, n, err)
  618. }
  619. WriteTo([]byte("}"), w, n, err)
  620. }
  621. case reflect.String:
  622. fallthrough
  623. case reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8, reflect.Uint:
  624. fallthrough
  625. case reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8, reflect.Int:
  626. fallthrough
  627. case reflect.Bool:
  628. jsonBytes, err_ := json.Marshal(rv.Interface())
  629. if err_ != nil {
  630. *err = err_
  631. return
  632. }
  633. WriteTo(jsonBytes, w, n, err)
  634. default:
  635. panic(Fmt("Unknown field type %v", rt.Kind()))
  636. }
  637. // Write TypeByte close bracket
  638. if typeInfo.HasTypeByte {
  639. WriteTo([]byte("]"), w, n, err)
  640. }
  641. }
  642. //-----------------------------------------------------------------------------