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.

844 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
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. if MaxBinaryReadSize < *n {
  249. *err = ErrBinaryReadSizeOverflow
  250. return
  251. }
  252. }
  253. sliceRv = reflect.AppendSlice(sliceRv, tmpSliceRv)
  254. }
  255. rv.Set(sliceRv)
  256. }
  257. case reflect.Struct:
  258. if rt == timeType {
  259. // Special case: time.Time
  260. t := ReadTime(r, n, err)
  261. log.Debug(Fmt("Read time: %v", t))
  262. rv.Set(reflect.ValueOf(t))
  263. } else {
  264. for _, fieldInfo := range typeInfo.Fields {
  265. i, fieldType, opts := fieldInfo.unpack()
  266. fieldRv := rv.Field(i)
  267. readReflectBinary(fieldRv, fieldType, opts, r, n, err)
  268. }
  269. }
  270. case reflect.String:
  271. str := ReadString(r, n, err)
  272. log.Debug(Fmt("Read string: %v", str))
  273. rv.SetString(str)
  274. case reflect.Int64:
  275. if opts.Varint {
  276. num := ReadVarint(r, n, err)
  277. log.Debug(Fmt("Read num: %v", num))
  278. rv.SetInt(int64(num))
  279. } else {
  280. num := ReadInt64(r, n, err)
  281. log.Debug(Fmt("Read num: %v", num))
  282. rv.SetInt(int64(num))
  283. }
  284. case reflect.Int32:
  285. num := ReadUint32(r, n, err)
  286. log.Debug(Fmt("Read num: %v", num))
  287. rv.SetInt(int64(num))
  288. case reflect.Int16:
  289. num := ReadUint16(r, n, err)
  290. log.Debug(Fmt("Read num: %v", num))
  291. rv.SetInt(int64(num))
  292. case reflect.Int8:
  293. num := ReadUint8(r, n, err)
  294. log.Debug(Fmt("Read num: %v", num))
  295. rv.SetInt(int64(num))
  296. case reflect.Int:
  297. num := ReadVarint(r, n, err)
  298. log.Debug(Fmt("Read num: %v", num))
  299. rv.SetInt(int64(num))
  300. case reflect.Uint64:
  301. if opts.Varint {
  302. num := ReadVarint(r, n, err)
  303. log.Debug(Fmt("Read num: %v", num))
  304. rv.SetUint(uint64(num))
  305. } else {
  306. num := ReadUint64(r, n, err)
  307. log.Debug(Fmt("Read num: %v", num))
  308. rv.SetUint(uint64(num))
  309. }
  310. case reflect.Uint32:
  311. num := ReadUint32(r, n, err)
  312. log.Debug(Fmt("Read num: %v", num))
  313. rv.SetUint(uint64(num))
  314. case reflect.Uint16:
  315. num := ReadUint16(r, n, err)
  316. log.Debug(Fmt("Read num: %v", num))
  317. rv.SetUint(uint64(num))
  318. case reflect.Uint8:
  319. num := ReadUint8(r, n, err)
  320. log.Debug(Fmt("Read num: %v", num))
  321. rv.SetUint(uint64(num))
  322. case reflect.Uint:
  323. num := ReadVarint(r, n, err)
  324. log.Debug(Fmt("Read num: %v", num))
  325. rv.SetUint(uint64(num))
  326. case reflect.Bool:
  327. num := ReadUint8(r, n, err)
  328. log.Debug(Fmt("Read bool: %v", num))
  329. rv.SetBool(num > 0)
  330. default:
  331. // SANITY CHECK
  332. panic(Fmt("Unknown field type %v", rt.Kind()))
  333. }
  334. }
  335. // rv: the reflection value of the thing to write
  336. // rt: the type of rv as declared in the container, not necessarily rv.Type().
  337. func writeReflectBinary(rv reflect.Value, rt reflect.Type, opts Options, w io.Writer, n *int64, err *error) {
  338. // Get typeInfo
  339. typeInfo := GetTypeInfo(rt)
  340. if rt.Kind() == reflect.Interface {
  341. if rv.IsNil() {
  342. // XXX ensure that typeByte 0 is reserved.
  343. WriteByte(0x00, w, n, err)
  344. return
  345. }
  346. crv := rv.Elem() // concrete reflection value
  347. crt := crv.Type() // concrete reflection type
  348. if typeInfo.IsRegisteredInterface {
  349. // See if the crt is registered.
  350. // If so, we're more restrictive.
  351. _, ok := typeInfo.TypeToByte[crt]
  352. if !ok {
  353. switch crt.Kind() {
  354. case reflect.Ptr:
  355. *err = errors.New(Fmt("Unexpected pointer type %v. Was it registered as a value receiver rather than as a pointer receiver?", crt))
  356. case reflect.Struct:
  357. *err = errors.New(Fmt("Unexpected struct type %v. Was it registered as a pointer receiver rather than as a value receiver?", crt))
  358. default:
  359. *err = errors.New(Fmt("Unexpected type %v.", crt))
  360. }
  361. return
  362. }
  363. } else {
  364. // We support writing unsafely for convenience.
  365. }
  366. // We don't have to write the typeByte here,
  367. // the writeReflectBinary() call below will write it.
  368. writeReflectBinary(crv, crt, opts, w, n, err)
  369. return
  370. }
  371. if rt.Kind() == reflect.Ptr {
  372. // Dereference pointer
  373. rv, rt = rv.Elem(), rt.Elem()
  374. typeInfo = GetTypeInfo(rt)
  375. if !rv.IsValid() {
  376. WriteByte(0x00, w, n, err)
  377. return
  378. }
  379. if typeInfo.Byte == 0x00 {
  380. WriteByte(0x01, w, n, err)
  381. // continue...
  382. } else {
  383. // continue...
  384. }
  385. }
  386. // Write type byte
  387. if typeInfo.Byte != 0x00 {
  388. WriteByte(typeInfo.Byte, w, n, err)
  389. }
  390. // All other types
  391. switch rt.Kind() {
  392. case reflect.Slice:
  393. elemRt := rt.Elem()
  394. if elemRt.Kind() == reflect.Uint8 {
  395. // Special case: Byteslices
  396. byteslice := rv.Bytes()
  397. WriteByteSlice(byteslice, w, n, err)
  398. } else {
  399. // Write length
  400. length := rv.Len()
  401. WriteVarint(length, w, n, err)
  402. // Write elems
  403. for i := 0; i < length; i++ {
  404. elemRv := rv.Index(i)
  405. writeReflectBinary(elemRv, elemRt, opts, w, n, err)
  406. }
  407. }
  408. case reflect.Struct:
  409. if rt == timeType {
  410. // Special case: time.Time
  411. WriteTime(rv.Interface().(time.Time), w, n, err)
  412. } else {
  413. for _, fieldInfo := range typeInfo.Fields {
  414. i, fieldType, opts := fieldInfo.unpack()
  415. fieldRv := rv.Field(i)
  416. writeReflectBinary(fieldRv, fieldType, opts, w, n, err)
  417. }
  418. }
  419. case reflect.String:
  420. WriteString(rv.String(), w, n, err)
  421. case reflect.Int64:
  422. if opts.Varint {
  423. WriteVarint(int(rv.Int()), w, n, err)
  424. } else {
  425. WriteInt64(rv.Int(), w, n, err)
  426. }
  427. case reflect.Int32:
  428. WriteInt32(int32(rv.Int()), w, n, err)
  429. case reflect.Int16:
  430. WriteInt16(int16(rv.Int()), w, n, err)
  431. case reflect.Int8:
  432. WriteInt8(int8(rv.Int()), w, n, err)
  433. case reflect.Int:
  434. WriteVarint(int(rv.Int()), w, n, err)
  435. case reflect.Uint64:
  436. if opts.Varint {
  437. WriteUvarint(uint(rv.Uint()), w, n, err)
  438. } else {
  439. WriteUint64(rv.Uint(), w, n, err)
  440. }
  441. case reflect.Uint32:
  442. WriteUint32(uint32(rv.Uint()), w, n, err)
  443. case reflect.Uint16:
  444. WriteUint16(uint16(rv.Uint()), w, n, err)
  445. case reflect.Uint8:
  446. WriteUint8(uint8(rv.Uint()), w, n, err)
  447. case reflect.Uint:
  448. WriteUvarint(uint(rv.Uint()), w, n, err)
  449. case reflect.Bool:
  450. if rv.Bool() {
  451. WriteUint8(uint8(1), w, n, err)
  452. } else {
  453. WriteUint8(uint8(0), w, n, err)
  454. }
  455. default:
  456. // SANITY CHECK
  457. panic(Fmt("Unknown field type %v", rt.Kind()))
  458. }
  459. }
  460. //-----------------------------------------------------------------------------
  461. func readByteJSON(o interface{}) (typeByte byte, rest interface{}, err error) {
  462. oSlice, ok := o.([]interface{})
  463. if !ok {
  464. err = errors.New(Fmt("Expected type [Byte,?] but got type %v", reflect.TypeOf(o)))
  465. return
  466. }
  467. if len(oSlice) != 2 {
  468. err = errors.New(Fmt("Expected [Byte,?] len 2 but got len %v", len(oSlice)))
  469. return
  470. }
  471. typeByte_, ok := oSlice[0].(float64)
  472. typeByte = byte(typeByte_)
  473. rest = oSlice[1]
  474. return
  475. }
  476. // Contract: Caller must ensure that rt is supported
  477. // (e.g. is recursively composed of supported native types, and structs and slices.)
  478. func readReflectJSON(rv reflect.Value, rt reflect.Type, o interface{}, err *error) {
  479. // Get typeInfo
  480. typeInfo := GetTypeInfo(rt)
  481. if rt.Kind() == reflect.Interface {
  482. if !typeInfo.IsRegisteredInterface {
  483. // There's no way we can read such a thing.
  484. *err = errors.New(Fmt("Cannot read unregistered interface type %v", rt))
  485. return
  486. }
  487. if o == nil {
  488. return // nil
  489. }
  490. typeByte, _, err_ := readByteJSON(o)
  491. if err_ != nil {
  492. *err = err_
  493. return
  494. }
  495. crt, ok := typeInfo.ByteToType[typeByte]
  496. if !ok {
  497. *err = errors.New(Fmt("Byte %X not registered for interface %v", typeByte, rt))
  498. return
  499. }
  500. crv := reflect.New(crt).Elem()
  501. readReflectJSON(crv, crt, o, err)
  502. rv.Set(crv) // NOTE: orig rv is ignored.
  503. return
  504. }
  505. if rt.Kind() == reflect.Ptr {
  506. if o == nil {
  507. return // nil
  508. }
  509. // Create new struct if rv is nil.
  510. if rv.IsNil() {
  511. newRv := reflect.New(rt.Elem())
  512. rv.Set(newRv)
  513. rv = newRv
  514. }
  515. // Dereference pointer
  516. rv, rt = rv.Elem(), rt.Elem()
  517. typeInfo = GetTypeInfo(rt)
  518. // continue...
  519. }
  520. // Read Byte prefix
  521. if typeInfo.Byte != 0x00 {
  522. typeByte, rest, err_ := readByteJSON(o)
  523. if err_ != nil {
  524. *err = err_
  525. return
  526. }
  527. if typeByte != typeInfo.Byte {
  528. *err = errors.New(Fmt("Expected Byte of %X but got %X", typeInfo.Byte, byte(typeByte)))
  529. return
  530. }
  531. o = rest
  532. }
  533. switch rt.Kind() {
  534. case reflect.Slice:
  535. elemRt := rt.Elem()
  536. if elemRt.Kind() == reflect.Uint8 {
  537. // Special case: Byteslices
  538. oString, ok := o.(string)
  539. if !ok {
  540. *err = errors.New(Fmt("Expected string but got type %v", reflect.TypeOf(o)))
  541. return
  542. }
  543. byteslice, err_ := hex.DecodeString(oString)
  544. if err_ != nil {
  545. *err = err_
  546. return
  547. }
  548. log.Debug("Read byteslice", "bytes", byteslice)
  549. rv.Set(reflect.ValueOf(byteslice))
  550. } else {
  551. // Read length
  552. oSlice, ok := o.([]interface{})
  553. if !ok {
  554. *err = errors.New(Fmt("Expected array of %v but got type %v", rt, reflect.TypeOf(o)))
  555. return
  556. }
  557. length := len(oSlice)
  558. log.Debug(Fmt("Read length: %v", length))
  559. sliceRv := reflect.MakeSlice(rt, length, length)
  560. // Read elems
  561. for i := 0; i < length; i++ {
  562. elemRv := sliceRv.Index(i)
  563. readReflectJSON(elemRv, elemRt, oSlice[i], err)
  564. }
  565. rv.Set(sliceRv)
  566. }
  567. case reflect.Struct:
  568. if rt == timeType {
  569. // Special case: time.Time
  570. str, ok := o.(string)
  571. if !ok {
  572. *err = errors.New(Fmt("Expected string but got type %v", reflect.TypeOf(o)))
  573. return
  574. }
  575. log.Debug(Fmt("Read time: %v", str))
  576. t, err_ := time.Parse(rfc2822, str)
  577. if err_ != nil {
  578. *err = err_
  579. return
  580. }
  581. rv.Set(reflect.ValueOf(t))
  582. } else {
  583. oMap, ok := o.(map[string]interface{})
  584. if !ok {
  585. *err = errors.New(Fmt("Expected map but got type %v", reflect.TypeOf(o)))
  586. return
  587. }
  588. // TODO: ensure that all fields are set?
  589. // TODO: disallow unknown oMap fields?
  590. for _, fieldInfo := range typeInfo.Fields {
  591. i, fieldType, opts := fieldInfo.unpack()
  592. value, ok := oMap[opts.JSONName]
  593. if !ok {
  594. continue // Skip missing fields.
  595. }
  596. fieldRv := rv.Field(i)
  597. readReflectJSON(fieldRv, fieldType, value, err)
  598. }
  599. }
  600. case reflect.String:
  601. str, ok := o.(string)
  602. if !ok {
  603. *err = errors.New(Fmt("Expected string but got type %v", reflect.TypeOf(o)))
  604. return
  605. }
  606. log.Debug(Fmt("Read string: %v", str))
  607. rv.SetString(str)
  608. case reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8, reflect.Int:
  609. num, ok := o.(float64)
  610. if !ok {
  611. *err = errors.New(Fmt("Expected numeric but got type %v", reflect.TypeOf(o)))
  612. return
  613. }
  614. log.Debug(Fmt("Read num: %v", num))
  615. rv.SetInt(int64(num))
  616. case reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8, reflect.Uint:
  617. num, ok := o.(float64)
  618. if !ok {
  619. *err = errors.New(Fmt("Expected numeric but got type %v", reflect.TypeOf(o)))
  620. return
  621. }
  622. if num < 0 {
  623. *err = errors.New(Fmt("Expected unsigned numeric but got %v", num))
  624. return
  625. }
  626. log.Debug(Fmt("Read num: %v", num))
  627. rv.SetUint(uint64(num))
  628. case reflect.Bool:
  629. bl, ok := o.(bool)
  630. if !ok {
  631. *err = errors.New(Fmt("Expected boolean but got type %v", reflect.TypeOf(o)))
  632. return
  633. }
  634. log.Debug(Fmt("Read boolean: %v", bl))
  635. rv.SetBool(bl)
  636. default:
  637. // SANITY CHECK
  638. panic(Fmt("Unknown field type %v", rt.Kind()))
  639. }
  640. }
  641. func writeReflectJSON(rv reflect.Value, rt reflect.Type, w io.Writer, n *int64, err *error) {
  642. log.Debug(Fmt("writeReflectJSON(%v, %v, %v, %v, %v)", rv, rt, w, n, err))
  643. // Get typeInfo
  644. typeInfo := GetTypeInfo(rt)
  645. if rt.Kind() == reflect.Interface {
  646. if rv.IsNil() {
  647. // XXX ensure that typeByte 0 is reserved.
  648. WriteTo([]byte("null"), w, n, err)
  649. return
  650. }
  651. crv := rv.Elem() // concrete reflection value
  652. crt := crv.Type() // concrete reflection type
  653. if typeInfo.IsRegisteredInterface {
  654. // See if the crt is registered.
  655. // If so, we're more restrictive.
  656. _, ok := typeInfo.TypeToByte[crt]
  657. if !ok {
  658. switch crt.Kind() {
  659. case reflect.Ptr:
  660. *err = errors.New(Fmt("Unexpected pointer type %v. Was it registered as a value receiver rather than as a pointer receiver?", crt))
  661. case reflect.Struct:
  662. *err = errors.New(Fmt("Unexpected struct type %v. Was it registered as a pointer receiver rather than as a value receiver?", crt))
  663. default:
  664. *err = errors.New(Fmt("Unexpected type %v.", crt))
  665. }
  666. return
  667. }
  668. } else {
  669. // We support writing unsafely for convenience.
  670. }
  671. // We don't have to write the typeByte here,
  672. // the writeReflectJSON() call below will write it.
  673. writeReflectJSON(crv, crt, w, n, err)
  674. return
  675. }
  676. if rt.Kind() == reflect.Ptr {
  677. // Dereference pointer
  678. rv, rt = rv.Elem(), rt.Elem()
  679. typeInfo = GetTypeInfo(rt)
  680. if !rv.IsValid() {
  681. WriteTo([]byte("null"), w, n, err)
  682. return
  683. }
  684. // continue...
  685. }
  686. // Write Byte
  687. if typeInfo.Byte != 0x00 {
  688. WriteTo([]byte(Fmt("[%v,", typeInfo.Byte)), w, n, err)
  689. defer WriteTo([]byte("]"), w, n, err)
  690. }
  691. // All other types
  692. switch rt.Kind() {
  693. case reflect.Slice:
  694. elemRt := rt.Elem()
  695. if elemRt.Kind() == reflect.Uint8 {
  696. // Special case: Byteslices
  697. byteslice := rv.Bytes()
  698. WriteTo([]byte(Fmt("\"%X\"", byteslice)), w, n, err)
  699. //WriteByteSlice(byteslice, w, n, err)
  700. } else {
  701. WriteTo([]byte("["), w, n, err)
  702. // Write elems
  703. length := rv.Len()
  704. for i := 0; i < length; i++ {
  705. elemRv := rv.Index(i)
  706. writeReflectJSON(elemRv, elemRt, w, n, err)
  707. if i < length-1 {
  708. WriteTo([]byte(","), w, n, err)
  709. }
  710. }
  711. WriteTo([]byte("]"), w, n, err)
  712. }
  713. case reflect.Struct:
  714. if rt == timeType {
  715. // Special case: time.Time
  716. t := rv.Interface().(time.Time)
  717. str := t.Format(rfc2822)
  718. jsonBytes, err_ := json.Marshal(str)
  719. if err_ != nil {
  720. *err = err_
  721. return
  722. }
  723. WriteTo(jsonBytes, w, n, err)
  724. } else {
  725. WriteTo([]byte("{"), w, n, err)
  726. wroteField := false
  727. for _, fieldInfo := range typeInfo.Fields {
  728. i, fieldType, opts := fieldInfo.unpack()
  729. fieldRv := rv.Field(i)
  730. if wroteField {
  731. WriteTo([]byte(","), w, n, err)
  732. } else {
  733. wroteField = true
  734. }
  735. WriteTo([]byte(Fmt("\"%v\":", opts.JSONName)), w, n, err)
  736. writeReflectJSON(fieldRv, fieldType, w, n, err)
  737. }
  738. WriteTo([]byte("}"), w, n, err)
  739. }
  740. case reflect.String:
  741. fallthrough
  742. case reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8, reflect.Uint:
  743. fallthrough
  744. case reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8, reflect.Int:
  745. fallthrough
  746. case reflect.Bool:
  747. jsonBytes, err_ := json.Marshal(rv.Interface())
  748. if err_ != nil {
  749. *err = err_
  750. return
  751. }
  752. WriteTo(jsonBytes, w, n, err)
  753. default:
  754. // SANITY CHECK
  755. panic(Fmt("Unknown field type %v", rt.Kind()))
  756. }
  757. }