github.com/wfusion/gofusion@v1.1.14/common/utils/serialize/unmarshal.go (about) 1 package serialize 2 3 import ( 4 "fmt" 5 "io" 6 "reflect" 7 8 "github.com/wfusion/gofusion/common/utils" 9 ) 10 11 func UnmarshalFunc[T any](algo Algorithm, opts ...utils.OptionExtender) func(src []byte) (T, error) { 12 fn, ok := unmarshalFuncMap[algo] 13 if !ok { 14 panic(fmt.Errorf("unknown serialize algorithm type %+v", algo)) 15 } 16 opt := utils.ApplyOptions[unmarshalOption](opts...) 17 return func(src []byte) (dst T, err error) { 18 bs, cb := utils.BytesBufferPool.Get(nil) 19 defer cb() 20 21 bs.Write(src) 22 err = fn(&dst, bs, opt) 23 return 24 } 25 } 26 27 func UnmarshalFuncByType(algo Algorithm, dst any, opts ...utils.OptionExtender) func([]byte) (any, error) { 28 fn, ok := unmarshalFuncMap[algo] 29 if !ok { 30 panic(fmt.Errorf("unknown serialize algorithm type %+v", algo)) 31 } 32 dstType, ok := dst.(reflect.Type) 33 if !ok { 34 dstType = reflect.TypeOf(dst) 35 } 36 opt := utils.ApplyOptions[unmarshalOption](opts...) 37 return func(src []byte) (dst any, err error) { 38 dst = reflect.New(dstType).Interface() 39 40 bs, cb := utils.BytesBufferPool.Get(nil) 41 defer cb() 42 43 bs.Write(src) 44 err = fn(dst, bs, opt) 45 return 46 } 47 } 48 49 func UnmarshalStreamFunc[T any](algo Algorithm, opts ...utils.OptionExtender) func(io.Reader) (T, error) { 50 fn, ok := unmarshalFuncMap[algo] 51 if !ok { 52 panic(fmt.Errorf("unknown serialize algorithm type %+v", algo)) 53 } 54 opt := utils.ApplyOptions[unmarshalOption](opts...) 55 return func(src io.Reader) (dst T, err error) { 56 err = fn(&dst, src, opt) 57 return 58 } 59 } 60 61 func UnmarshalStreamFuncByType(algo Algorithm, dst any, opts ...utils.OptionExtender) func(io.Reader) (any, error) { 62 fn, ok := unmarshalFuncMap[algo] 63 if !ok { 64 panic(fmt.Errorf("unknown serialize algorithm type %+v", algo)) 65 } 66 dstType, ok := dst.(reflect.Type) 67 if !ok { 68 dstType = reflect.TypeOf(dst) 69 } 70 opt := utils.ApplyOptions[unmarshalOption](opts...) 71 return func(src io.Reader) (dst any, err error) { 72 d := reflect.New(dstType).Interface() 73 if err = fn(d, src, opt); err != nil { 74 return 75 } 76 dst = reflect.Indirect(reflect.ValueOf(d)).Interface() 77 return 78 } 79 }