/usr/share/gocode/src/github.com/tendermint/go-wire/reflect.go is in golang-github-tendermint-go-wire-dev 0~20161027~0git287d8ca-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 | package wire
import (
"encoding/hex"
"encoding/json"
"errors"
"io"
"reflect"
"strings"
"sync"
"time"
. "github.com/tendermint/go-common"
)
type TypeInfo struct {
Type reflect.Type // The type
// If Type is kind reflect.Interface, is registered
IsRegisteredInterface bool
ByteToType map[byte]reflect.Type
TypeToByte map[reflect.Type]byte
// If Type is kind reflect.Struct
Fields []StructFieldInfo
Unwrap bool // if struct has only one field and its an anonymous interface
}
type Options struct {
JSONName string // (JSON) Corresponding JSON field name. (override with `json=""`)
JSONOmitEmpty bool // (JSON) Omit field if value is empty
Varint bool // (Binary) Use length-prefixed encoding for (u)int64
Unsafe bool // (JSON/Binary) Explicitly enable support for floats or maps
ZeroValue interface{} // Prototype zero object
}
func getOptionsFromField(field reflect.StructField) (skip bool, opts Options) {
jsonTag := field.Tag.Get("json")
binTag := field.Tag.Get("binary")
wireTag := field.Tag.Get("wire")
if jsonTag == "-" {
skip = true
return
}
jsonTagParts := strings.Split(jsonTag, ",")
if jsonTagParts[0] == "" {
opts.JSONName = field.Name
} else {
opts.JSONName = jsonTagParts[0]
}
if len(jsonTagParts) > 1 {
if jsonTagParts[1] == "omitempty" {
opts.JSONOmitEmpty = true
}
}
if binTag == "varint" { // TODO: extend
opts.Varint = true
}
if wireTag == "unsafe" {
opts.Unsafe = true
}
opts.ZeroValue = reflect.Zero(field.Type).Interface()
return
}
type StructFieldInfo struct {
Index int // Struct field index
Type reflect.Type // Struct field type
Options // Encoding options
}
func (info StructFieldInfo) unpack() (int, reflect.Type, Options) {
return info.Index, info.Type, info.Options
}
// e.g. If o is struct{Foo}{}, return is the Foo reflection type.
func GetTypeFromStructDeclaration(o interface{}) reflect.Type {
rt := reflect.TypeOf(o)
if rt.NumField() != 1 {
PanicSanity("Unexpected number of fields in struct-wrapped declaration of type")
}
return rt.Field(0).Type
}
// Predeclaration of common types
var (
timeType = GetTypeFromStructDeclaration(struct{ time.Time }{})
)
const (
iso8601 = "2006-01-02T15:04:05.000Z" // forced microseconds
)
// NOTE: do not access typeInfos directly, but call GetTypeInfo()
var typeInfosMtx sync.RWMutex
var typeInfos = map[reflect.Type]*TypeInfo{}
func GetTypeInfo(rt reflect.Type) *TypeInfo {
typeInfosMtx.RLock()
info := typeInfos[rt]
typeInfosMtx.RUnlock()
if info == nil {
info = MakeTypeInfo(rt)
typeInfosMtx.Lock()
typeInfos[rt] = info
typeInfosMtx.Unlock()
}
return info
}
// For use with the RegisterInterface declaration
type ConcreteType struct {
O interface{}
Byte byte
}
// Must use this to register an interface to properly decode the
// underlying concrete type.
func RegisterInterface(o interface{}, ctypes ...ConcreteType) *TypeInfo {
it := GetTypeFromStructDeclaration(o)
if it.Kind() != reflect.Interface {
PanicSanity("RegisterInterface expects an interface")
}
toType := make(map[byte]reflect.Type, 0)
toByte := make(map[reflect.Type]byte, 0)
for _, ctype := range ctypes {
crt := reflect.TypeOf(ctype.O)
typeByte := ctype.Byte
if typeByte == 0x00 {
PanicSanity(Fmt("Byte of 0x00 is reserved for nil (%v)", ctype))
}
if toType[typeByte] != nil {
PanicSanity(Fmt("Duplicate Byte for type %v and %v", ctype, toType[typeByte]))
}
toType[typeByte] = crt
toByte[crt] = typeByte
}
typeInfo := &TypeInfo{
Type: it,
IsRegisteredInterface: true,
ByteToType: toType,
TypeToByte: toByte,
}
typeInfos[it] = typeInfo
return typeInfo
}
func MakeTypeInfo(rt reflect.Type) *TypeInfo {
info := &TypeInfo{Type: rt}
// If struct, register field name options
if rt.Kind() == reflect.Struct {
numFields := rt.NumField()
structFields := []StructFieldInfo{}
for i := 0; i < numFields; i++ {
field := rt.Field(i)
if field.PkgPath != "" {
continue
}
skip, opts := getOptionsFromField(field)
if skip {
continue
}
structFields = append(structFields, StructFieldInfo{
Index: i,
Type: field.Type,
Options: opts,
})
}
info.Fields = structFields
// Maybe type is a wrapper.
if len(structFields) == 1 {
jsonName := rt.Field(structFields[0].Index).Tag.Get("json")
if jsonName == "unwrap" {
info.Unwrap = true
}
}
}
return info
}
// Contract: Caller must ensure that rt is supported
// (e.g. is recursively composed of supported native types, and structs and slices.)
func readReflectBinary(rv reflect.Value, rt reflect.Type, opts Options, r io.Reader, lmt int, n *int, err *error) {
// Get typeInfo
typeInfo := GetTypeInfo(rt)
if rt.Kind() == reflect.Interface {
if !typeInfo.IsRegisteredInterface {
// There's no way we can read such a thing.
*err = errors.New(Fmt("Cannot read unregistered interface type %v", rt))
return
}
typeByte := ReadByte(r, n, err)
if *err != nil {
return
}
if typeByte == 0x00 {
return // nil
}
crt, ok := typeInfo.ByteToType[typeByte]
if !ok {
*err = errors.New(Fmt("Unexpected type byte %X for type %v", typeByte, rt))
return
}
if crt.Kind() == reflect.Ptr {
crt = crt.Elem()
crv := reflect.New(crt)
readReflectBinary(crv.Elem(), crt, opts, r, lmt, n, err)
rv.Set(crv) // NOTE: orig rv is ignored.
} else {
crv := reflect.New(crt).Elem()
readReflectBinary(crv, crt, opts, r, lmt, n, err)
rv.Set(crv) // NOTE: orig rv is ignored.
}
return
}
if rt.Kind() == reflect.Ptr {
typeByte := ReadByte(r, n, err)
if *err != nil {
return
}
if typeByte == 0x00 {
return // nil
} else if typeByte != 0x01 {
*err = errors.New(Fmt("Unexpected type byte %X for ptr of untyped thing", typeByte))
return
}
// Create new if rv is nil.
if rv.IsNil() {
newRv := reflect.New(rt.Elem())
rv.Set(newRv)
rv = newRv
}
// Dereference pointer
rv, rt = rv.Elem(), rt.Elem()
typeInfo = GetTypeInfo(rt)
// continue...
}
switch rt.Kind() {
case reflect.Array:
elemRt := rt.Elem()
length := rt.Len()
if elemRt.Kind() == reflect.Uint8 {
// Special case: Bytearrays
buf := make([]byte, length)
ReadFull(buf, r, n, err)
if *err != nil {
return
}
//log.Info("Read bytearray", "bytes", buf, "n", *n)
reflect.Copy(rv, reflect.ValueOf(buf))
} else {
for i := 0; i < length; i++ {
elemRv := rv.Index(i)
readReflectBinary(elemRv, elemRt, opts, r, lmt, n, err)
if *err != nil {
return
}
if lmt != 0 && lmt < *n {
*err = ErrBinaryReadOverflow
return
}
}
//log.Info("Read x-array", "x", elemRt, "length", length, "n", *n)
}
case reflect.Slice:
elemRt := rt.Elem()
if elemRt.Kind() == reflect.Uint8 {
// Special case: Byteslices
byteslice := ReadByteSlice(r, lmt, n, err)
//log.Info("Read byteslice", "bytes", byteslice, "n", *n)
rv.Set(reflect.ValueOf(byteslice))
} else {
var sliceRv reflect.Value
// Read length
length := ReadVarint(r, n, err)
//log.Info("Read slice", "length", length, "n", *n)
sliceRv = reflect.MakeSlice(rt, 0, 0)
// read one ReadSliceChunkSize at a time and append
for i := 0; i*ReadSliceChunkSize < length; i++ {
l := MinInt(ReadSliceChunkSize, length-i*ReadSliceChunkSize)
tmpSliceRv := reflect.MakeSlice(rt, l, l)
for j := 0; j < l; j++ {
elemRv := tmpSliceRv.Index(j)
readReflectBinary(elemRv, elemRt, opts, r, lmt, n, err)
if *err != nil {
return
}
if lmt != 0 && lmt < *n {
*err = ErrBinaryReadOverflow
return
}
}
sliceRv = reflect.AppendSlice(sliceRv, tmpSliceRv)
}
rv.Set(sliceRv)
}
case reflect.Struct:
if rt == timeType {
// Special case: time.Time
t := ReadTime(r, n, err)
//log.Info("Read time", "t", t, "n", *n)
rv.Set(reflect.ValueOf(t))
} else {
for _, fieldInfo := range typeInfo.Fields {
fieldIdx, fieldType, opts := fieldInfo.unpack()
fieldRv := rv.Field(fieldIdx)
readReflectBinary(fieldRv, fieldType, opts, r, lmt, n, err)
}
}
case reflect.String:
str := ReadString(r, lmt, n, err)
//log.Info("Read string", "str", str, "n", *n)
rv.SetString(str)
case reflect.Int64:
if opts.Varint {
num := ReadVarint(r, n, err)
//log.Info("Read num", "num", num, "n", *n)
rv.SetInt(int64(num))
} else {
num := ReadInt64(r, n, err)
//log.Info("Read num", "num", num, "n", *n)
rv.SetInt(int64(num))
}
case reflect.Int32:
num := ReadUint32(r, n, err)
//log.Info("Read num", "num", num, "n", *n)
rv.SetInt(int64(num))
case reflect.Int16:
num := ReadUint16(r, n, err)
//log.Info("Read num", "num", num, "n", *n)
rv.SetInt(int64(num))
case reflect.Int8:
num := ReadUint8(r, n, err)
//log.Info("Read num", "num", num, "n", *n)
rv.SetInt(int64(num))
case reflect.Int:
num := ReadVarint(r, n, err)
//log.Info("Read num", "num", num, "n", *n)
rv.SetInt(int64(num))
case reflect.Uint64:
if opts.Varint {
num := ReadVarint(r, n, err)
//log.Info("Read num", "num", num, "n", *n)
rv.SetUint(uint64(num))
} else {
num := ReadUint64(r, n, err)
//log.Info("Read num", "num", num, "n", *n)
rv.SetUint(uint64(num))
}
case reflect.Uint32:
num := ReadUint32(r, n, err)
//log.Info("Read num", "num", num, "n", *n)
rv.SetUint(uint64(num))
case reflect.Uint16:
num := ReadUint16(r, n, err)
//log.Info("Read num", "num", num, "n", *n)
rv.SetUint(uint64(num))
case reflect.Uint8:
num := ReadUint8(r, n, err)
//log.Info("Read num", "num", num, "n", *n)
rv.SetUint(uint64(num))
case reflect.Uint:
num := ReadVarint(r, n, err)
//log.Info("Read num", "num", num, "n", *n)
rv.SetUint(uint64(num))
case reflect.Bool:
num := ReadUint8(r, n, err)
//log.Info("Read bool", "bool", num, "n", *n)
rv.SetBool(num > 0)
case reflect.Float64:
if !opts.Unsafe {
*err = errors.New("Wire float* support requires `wire:\"unsafe\"`")
return
}
num := ReadFloat64(r, n, err)
//log.Info("Read num", "num", num, "n", *n)
rv.SetFloat(float64(num))
case reflect.Float32:
if !opts.Unsafe {
*err = errors.New("Wire float* support requires `wire:\"unsafe\"`")
return
}
num := ReadFloat32(r, n, err)
//log.Info("Read num", "num", num, "n", *n)
rv.SetFloat(float64(num))
default:
PanicSanity(Fmt("Unknown field type %v", rt.Kind()))
}
}
// rv: the reflection value of the thing to write
// rt: the type of rv as declared in the container, not necessarily rv.Type().
func writeReflectBinary(rv reflect.Value, rt reflect.Type, opts Options, w io.Writer, n *int, err *error) {
// Get typeInfo
typeInfo := GetTypeInfo(rt)
if rt.Kind() == reflect.Interface {
if rv.IsNil() {
WriteByte(0x00, w, n, err)
return
}
crv := rv.Elem() // concrete reflection value
crt := crv.Type() // concrete reflection type
if typeInfo.IsRegisteredInterface {
// See if the crt is registered.
// If so, we're more restrictive.
typeByte, ok := typeInfo.TypeToByte[crt]
if !ok {
switch crt.Kind() {
case reflect.Ptr:
*err = errors.New(Fmt("Unexpected pointer type %v for registered interface %v. "+
"Was it registered as a value receiver rather than as a pointer receiver?", crt, rt.Name()))
case reflect.Struct:
*err = errors.New(Fmt("Unexpected struct type %v for registered interface %v. "+
"Was it registered as a pointer receiver rather than as a value receiver?", crt, rt.Name()))
default:
*err = errors.New(Fmt("Unexpected type %v for registered interface %v. "+
"If this is intentional, please register it.", crt, rt.Name()))
}
return
}
if crt.Kind() == reflect.Ptr {
crv, crt = crv.Elem(), crt.Elem()
if !crv.IsValid() {
*err = errors.New(Fmt("Unexpected nil-pointer of type %v for registered interface %v. "+
"For compatibility with other languages, nil-pointer interface values are forbidden.", crt, rt.Name()))
return
}
}
WriteByte(typeByte, w, n, err)
writeReflectBinary(crv, crt, opts, w, n, err)
} else {
// We support writing unregistered interfaces for convenience.
writeReflectBinary(crv, crt, opts, w, n, err)
}
return
}
if rt.Kind() == reflect.Ptr {
// Dereference pointer
rv, rt = rv.Elem(), rt.Elem()
typeInfo = GetTypeInfo(rt)
if !rv.IsValid() {
WriteByte(0x00, w, n, err)
return
} else {
WriteByte(0x01, w, n, err)
// continue...
}
}
// All other types
switch rt.Kind() {
case reflect.Array:
elemRt := rt.Elem()
length := rt.Len()
if elemRt.Kind() == reflect.Uint8 {
// Special case: Bytearrays
if rv.CanAddr() {
byteslice := rv.Slice(0, length).Bytes()
WriteTo(byteslice, w, n, err)
} else {
buf := make([]byte, length)
reflect.Copy(reflect.ValueOf(buf), rv) // XXX: looks expensive!
WriteTo(buf, w, n, err)
}
} else {
// Write elems
for i := 0; i < length; i++ {
elemRv := rv.Index(i)
writeReflectBinary(elemRv, elemRt, opts, w, n, err)
}
}
case reflect.Slice:
elemRt := rt.Elem()
if elemRt.Kind() == reflect.Uint8 {
// Special case: Byteslices
byteslice := rv.Bytes()
WriteByteSlice(byteslice, w, n, err)
} else {
// Write length
length := rv.Len()
WriteVarint(length, w, n, err)
// Write elems
for i := 0; i < length; i++ {
elemRv := rv.Index(i)
writeReflectBinary(elemRv, elemRt, opts, w, n, err)
}
}
case reflect.Struct:
if rt == timeType {
// Special case: time.Time
WriteTime(rv.Interface().(time.Time), w, n, err)
} else {
for _, fieldInfo := range typeInfo.Fields {
fieldIdx, fieldType, opts := fieldInfo.unpack()
fieldRv := rv.Field(fieldIdx)
writeReflectBinary(fieldRv, fieldType, opts, w, n, err)
}
}
case reflect.String:
WriteString(rv.String(), w, n, err)
case reflect.Int64:
if opts.Varint {
WriteVarint(int(rv.Int()), w, n, err)
} else {
WriteInt64(rv.Int(), w, n, err)
}
case reflect.Int32:
WriteInt32(int32(rv.Int()), w, n, err)
case reflect.Int16:
WriteInt16(int16(rv.Int()), w, n, err)
case reflect.Int8:
WriteInt8(int8(rv.Int()), w, n, err)
case reflect.Int:
WriteVarint(int(rv.Int()), w, n, err)
case reflect.Uint64:
if opts.Varint {
WriteUvarint(uint(rv.Uint()), w, n, err)
} else {
WriteUint64(rv.Uint(), w, n, err)
}
case reflect.Uint32:
WriteUint32(uint32(rv.Uint()), w, n, err)
case reflect.Uint16:
WriteUint16(uint16(rv.Uint()), w, n, err)
case reflect.Uint8:
WriteUint8(uint8(rv.Uint()), w, n, err)
case reflect.Uint:
WriteUvarint(uint(rv.Uint()), w, n, err)
case reflect.Bool:
if rv.Bool() {
WriteUint8(uint8(1), w, n, err)
} else {
WriteUint8(uint8(0), w, n, err)
}
case reflect.Float64:
if !opts.Unsafe {
*err = errors.New("Wire float* support requires `wire:\"unsafe\"`")
return
}
WriteFloat64(rv.Float(), w, n, err)
case reflect.Float32:
if !opts.Unsafe {
*err = errors.New("Wire float* support requires `wire:\"unsafe\"`")
return
}
WriteFloat32(float32(rv.Float()), w, n, err)
default:
PanicSanity(Fmt("Unknown field type %v", rt.Kind()))
}
}
//-----------------------------------------------------------------------------
func readByteJSON(o interface{}) (typeByte byte, rest interface{}, err error) {
oSlice, ok := o.([]interface{})
if !ok {
err = errors.New(Fmt("Expected type [Byte,?] but got type %v", reflect.TypeOf(o)))
return
}
if len(oSlice) != 2 {
err = errors.New(Fmt("Expected [Byte,?] len 2 but got len %v", len(oSlice)))
return
}
typeByte_, ok := oSlice[0].(float64)
typeByte = byte(typeByte_)
rest = oSlice[1]
return
}
// Contract: Caller must ensure that rt is supported
// (e.g. is recursively composed of supported native types, and structs and slices.)
// rv and rt refer to the object we're unmarhsaling into, whereas o is the result of naiive json unmarshal (map[string]interface{})
func readReflectJSON(rv reflect.Value, rt reflect.Type, opts Options, o interface{}, err *error) {
// Get typeInfo
typeInfo := GetTypeInfo(rt)
if rt.Kind() == reflect.Interface {
if !typeInfo.IsRegisteredInterface {
// There's no way we can read such a thing.
*err = errors.New(Fmt("Cannot read unregistered interface type %v", rt))
return
}
if o == nil {
return // nil
}
typeByte, rest, err_ := readByteJSON(o)
if err_ != nil {
*err = err_
return
}
crt, ok := typeInfo.ByteToType[typeByte]
if !ok {
*err = errors.New(Fmt("Byte %X not registered for interface %v", typeByte, rt))
return
}
if crt.Kind() == reflect.Ptr {
crt = crt.Elem()
crv := reflect.New(crt)
readReflectJSON(crv.Elem(), crt, opts, rest, err)
rv.Set(crv) // NOTE: orig rv is ignored.
} else {
crv := reflect.New(crt).Elem()
readReflectJSON(crv, crt, opts, rest, err)
rv.Set(crv) // NOTE: orig rv is ignored.
}
return
}
if rt.Kind() == reflect.Ptr {
if o == nil {
return // nil
}
// Create new struct if rv is nil.
if rv.IsNil() {
newRv := reflect.New(rt.Elem())
rv.Set(newRv)
rv = newRv
}
// Dereference pointer
rv, rt = rv.Elem(), rt.Elem()
typeInfo = GetTypeInfo(rt)
// continue...
}
switch rt.Kind() {
case reflect.Array:
elemRt := rt.Elem()
length := rt.Len()
if elemRt.Kind() == reflect.Uint8 {
// Special case: Bytearrays
oString, ok := o.(string)
if !ok {
*err = errors.New(Fmt("Expected string but got type %v", reflect.TypeOf(o)))
return
}
buf, err_ := hex.DecodeString(oString)
if err_ != nil {
*err = err_
return
}
if len(buf) != length {
*err = errors.New(Fmt("Expected bytearray of length %v but got %v", length, len(buf)))
return
}
//log.Info("Read bytearray", "bytes", buf)
reflect.Copy(rv, reflect.ValueOf(buf))
} else {
oSlice, ok := o.([]interface{})
if !ok {
*err = errors.New(Fmt("Expected array of %v but got type %v", rt, reflect.TypeOf(o)))
return
}
if len(oSlice) != length {
*err = errors.New(Fmt("Expected array of length %v but got %v", length, len(oSlice)))
return
}
for i := 0; i < length; i++ {
elemRv := rv.Index(i)
readReflectJSON(elemRv, elemRt, opts, oSlice[i], err)
}
//log.Info("Read x-array", "x", elemRt, "length", length)
}
case reflect.Slice:
elemRt := rt.Elem()
if elemRt.Kind() == reflect.Uint8 {
// Special case: Byteslices
oString, ok := o.(string)
if !ok {
*err = errors.New(Fmt("Expected string but got type %v", reflect.TypeOf(o)))
return
}
byteslice, err_ := hex.DecodeString(oString)
if err_ != nil {
*err = err_
return
}
//log.Info("Read byteslice", "bytes", byteslice)
rv.Set(reflect.ValueOf(byteslice))
} else {
// Read length
oSlice, ok := o.([]interface{})
if !ok {
*err = errors.New(Fmt("Expected array of %v but got type %v", rt, reflect.TypeOf(o)))
return
}
length := len(oSlice)
//log.Info("Read slice", "length", length)
sliceRv := reflect.MakeSlice(rt, length, length)
// Read elems
for i := 0; i < length; i++ {
elemRv := sliceRv.Index(i)
readReflectJSON(elemRv, elemRt, opts, oSlice[i], err)
}
rv.Set(sliceRv)
}
case reflect.Struct:
if rt == timeType {
// Special case: time.Time
str, ok := o.(string)
if !ok {
*err = errors.New(Fmt("Expected string but got type %v", reflect.TypeOf(o)))
return
}
//log.Info("Read time", "t", str)
t, err_ := time.Parse(iso8601, str)
if err_ != nil {
*err = err_
return
}
rv.Set(reflect.ValueOf(t))
} else {
if typeInfo.Unwrap {
fieldIdx, fieldType, opts := typeInfo.Fields[0].unpack()
fieldRv := rv.Field(fieldIdx)
readReflectJSON(fieldRv, fieldType, opts, o, err)
} else {
oMap, ok := o.(map[string]interface{})
if !ok {
*err = errors.New(Fmt("Expected map but got type %v", reflect.TypeOf(o)))
return
}
// TODO: ensure that all fields are set?
// TODO: disallow unknown oMap fields?
for _, fieldInfo := range typeInfo.Fields {
fieldIdx, fieldType, opts := fieldInfo.unpack()
value, ok := oMap[opts.JSONName]
if !ok {
continue // Skip missing fields.
}
fieldRv := rv.Field(fieldIdx)
readReflectJSON(fieldRv, fieldType, opts, value, err)
}
}
}
case reflect.String:
str, ok := o.(string)
if !ok {
*err = errors.New(Fmt("Expected string but got type %v", reflect.TypeOf(o)))
return
}
//log.Info("Read string", "str", str)
rv.SetString(str)
case reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8, reflect.Int:
num, ok := o.(float64)
if !ok {
*err = errors.New(Fmt("Expected numeric but got type %v", reflect.TypeOf(o)))
return
}
//log.Info("Read num", "num", num)
rv.SetInt(int64(num))
case reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8, reflect.Uint:
num, ok := o.(float64)
if !ok {
*err = errors.New(Fmt("Expected numeric but got type %v", reflect.TypeOf(o)))
return
}
if num < 0 {
*err = errors.New(Fmt("Expected unsigned numeric but got %v", num))
return
}
//log.Info("Read num", "num", num)
rv.SetUint(uint64(num))
case reflect.Float64, reflect.Float32:
if !opts.Unsafe {
*err = errors.New("Wire float* support requires `wire:\"unsafe\"`")
return
}
num, ok := o.(float64)
if !ok {
*err = errors.New(Fmt("Expected numeric but got type %v", reflect.TypeOf(o)))
return
}
//log.Info("Read num", "num", num)
rv.SetFloat(num)
case reflect.Bool:
bl, ok := o.(bool)
if !ok {
*err = errors.New(Fmt("Expected boolean but got type %v", reflect.TypeOf(o)))
return
}
//log.Info("Read boolean", "boolean", bl)
rv.SetBool(bl)
default:
PanicSanity(Fmt("Unknown field type %v", rt.Kind()))
}
}
func writeReflectJSON(rv reflect.Value, rt reflect.Type, opts Options, w io.Writer, n *int, err *error) {
//log.Info(Fmt("writeReflectJSON(%v, %v, %v, %v, %v)", rv, rt, w, n, err))
// Get typeInfo
typeInfo := GetTypeInfo(rt)
if rt.Kind() == reflect.Interface {
if rv.IsNil() {
WriteTo([]byte("null"), w, n, err)
return
}
crv := rv.Elem() // concrete reflection value
crt := crv.Type() // concrete reflection type
if typeInfo.IsRegisteredInterface {
// See if the crt is registered.
// If so, we're more restrictive.
typeByte, ok := typeInfo.TypeToByte[crt]
if !ok {
switch crt.Kind() {
case reflect.Ptr:
*err = errors.New(Fmt("Unexpected pointer type %v for registered interface %v. "+
"Was it registered as a value receiver rather than as a pointer receiver?", crt, rt.Name()))
case reflect.Struct:
*err = errors.New(Fmt("Unexpected struct type %v for registered interface %v. "+
"Was it registered as a pointer receiver rather than as a value receiver?", crt, rt.Name()))
default:
*err = errors.New(Fmt("Unexpected type %v for registered interface %v. "+
"If this is intentional, please register it.", crt, rt.Name()))
}
return
}
if crt.Kind() == reflect.Ptr {
crv, crt = crv.Elem(), crt.Elem()
if !crv.IsValid() {
*err = errors.New(Fmt("Unexpected nil-pointer of type %v for registered interface %v. "+
"For compatibility with other languages, nil-pointer interface values are forbidden.", crt, rt.Name()))
return
}
}
WriteTo([]byte(Fmt("[%v,", typeByte)), w, n, err)
writeReflectJSON(crv, crt, opts, w, n, err)
WriteTo([]byte("]"), w, n, err)
} else {
// We support writing unregistered interfaces for convenience.
writeReflectJSON(crv, crt, opts, w, n, err)
}
return
}
if rt.Kind() == reflect.Ptr {
// Dereference pointer
rv, rt = rv.Elem(), rt.Elem()
typeInfo = GetTypeInfo(rt)
if !rv.IsValid() {
// For better compatibility with other languages,
// as far as tendermint/wire is concerned,
// pointers to nil values are the same as nil.
WriteTo([]byte("null"), w, n, err)
return
}
// continue...
}
// All other types
switch rt.Kind() {
case reflect.Array:
elemRt := rt.Elem()
length := rt.Len()
if elemRt.Kind() == reflect.Uint8 {
// Special case: Bytearray
bytearray := reflect.ValueOf(make([]byte, length))
reflect.Copy(bytearray, rv)
WriteTo([]byte(Fmt("\"%X\"", bytearray.Interface())), w, n, err)
} else {
WriteTo([]byte("["), w, n, err)
// Write elems
for i := 0; i < length; i++ {
elemRv := rv.Index(i)
writeReflectJSON(elemRv, elemRt, opts, w, n, err)
if i < length-1 {
WriteTo([]byte(","), w, n, err)
}
}
WriteTo([]byte("]"), w, n, err)
}
case reflect.Slice:
elemRt := rt.Elem()
if elemRt.Kind() == reflect.Uint8 {
// Special case: Byteslices
byteslice := rv.Bytes()
WriteTo([]byte(Fmt("\"%X\"", byteslice)), w, n, err)
} else {
WriteTo([]byte("["), w, n, err)
// Write elems
length := rv.Len()
for i := 0; i < length; i++ {
elemRv := rv.Index(i)
writeReflectJSON(elemRv, elemRt, opts, w, n, err)
if i < length-1 {
WriteTo([]byte(","), w, n, err)
}
}
WriteTo([]byte("]"), w, n, err)
}
case reflect.Struct:
if rt == timeType {
// Special case: time.Time
t := rv.Interface().(time.Time).UTC()
str := t.Format(iso8601)
jsonBytes, err_ := json.Marshal(str)
if err_ != nil {
*err = err_
return
}
WriteTo(jsonBytes, w, n, err)
} else {
if typeInfo.Unwrap {
fieldIdx, fieldType, opts := typeInfo.Fields[0].unpack()
fieldRv := rv.Field(fieldIdx)
writeReflectJSON(fieldRv, fieldType, opts, w, n, err)
} else {
WriteTo([]byte("{"), w, n, err)
wroteField := false
for _, fieldInfo := range typeInfo.Fields {
fieldIdx, fieldType, opts := fieldInfo.unpack()
fieldRv := rv.Field(fieldIdx)
if opts.JSONOmitEmpty { // Skip zero value if omitempty
if !fieldType.Comparable() && fieldRv.Len() == 0 {
continue
} else if fieldRv.Interface() == opts.ZeroValue {
continue
}
}
if wroteField {
WriteTo([]byte(","), w, n, err)
} else {
wroteField = true
}
WriteTo([]byte(Fmt("\"%v\":", opts.JSONName)), w, n, err)
writeReflectJSON(fieldRv, fieldType, opts, w, n, err)
}
WriteTo([]byte("}"), w, n, err)
}
}
case reflect.String:
fallthrough
case reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8, reflect.Uint:
fallthrough
case reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8, reflect.Int:
fallthrough
case reflect.Bool:
jsonBytes, err_ := json.Marshal(rv.Interface())
if err_ != nil {
*err = err_
return
}
WriteTo(jsonBytes, w, n, err)
case reflect.Float64, reflect.Float32:
if !opts.Unsafe {
*err = errors.New("Wire float* support requires `wire:\"unsafe\"`")
return
}
jsonBytes, err_ := json.Marshal(rv.Interface())
if err_ != nil {
*err = err_
return
}
WriteTo(jsonBytes, w, n, err)
default:
PanicSanity(Fmt("Unknown field type %v", rt.Kind()))
}
}
|