Skip to content
Permalink
Browse files
优化为switch方式
  • Loading branch information
Changeden committed Oct 12, 2021
1 parent 5bdf65a commit 53cd523c2d4740d4ca4291f7e185b23e9042e76e
Showing 1 changed file with 5 additions and 22 deletions.
@@ -19,7 +19,6 @@ package hessian

import (
"reflect"
"regexp"
"time"
"unsafe"
)
@@ -28,10 +27,6 @@ import (
perrors "github.com/pkg/errors"
)

var (
decodeTypeRegexp = regexp.MustCompile(`^(string|u?int(8|16|32|64)?|bool|float(32|64))$`)
)

// nil bool int8 int32 int64 float32 float64 time.Time
// string []byte []interface{} map[interface{}]interface{}
// array object struct
@@ -163,14 +158,15 @@ func (e *Encoder) Encode(v interface{}) error {
default:
t := UnpackPtrType(reflect.TypeOf(v))

if decodeTypeRegexp.Match([]byte(t.String())) { // unpack base type
switch t.Kind() {
case reflect.String, reflect.Bool,
reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
reflect.Float32, reflect.Float64: // solve base type
vVal := reflect.ValueOf(v)
if !vVal.IsNil() {
return e.Encode(vVal.Elem().Interface())
}
}

switch t.Kind() {
case reflect.Struct:
vv := reflect.ValueOf(v)
vv = UnpackPtr(vv)
@@ -195,19 +191,6 @@ func (e *Encoder) Encode(v interface{}) error {
return e.encList(v)
case reflect.Map: // the type must be map[string]int
return e.encMap(v)
case reflect.Bool:
vv := v.(*bool)
if vv != nil {
e.buffer = encBool(e.buffer, *vv)
} else {
e.buffer = encBool(e.buffer, false)
}
case reflect.Int32:
var err error
e.buffer, err = e.encTypeInt32(e.buffer, v)
if err != nil {
return err
}
default:
return perrors.Errorf("type not supported! %s", t.Kind().String())
}

0 comments on commit 53cd523

Please sign in to comment.