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.

840 lines
20 KiB

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