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.

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