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.

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