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.

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