From 59c8421597854a99840027e73b962d48e601292b Mon Sep 17 00:00:00 2001 From: Evgenii Stratonikov Date: Wed, 26 Jul 2023 16:53:20 +0300 Subject: [PATCH] [#49] util/proto: Use StableSize() to determine if the struct is empty `reflect` is not necessary here, and checking `StableSize` is what we _want_ anyway. Signed-off-by: Evgenii Stratonikov --- status/marshal.go | 4 ++++ util/proto/marshal.go | 10 ++++------ 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/status/marshal.go b/status/marshal.go index 78064c1..1868a43 100644 --- a/status/marshal.go +++ b/status/marshal.go @@ -69,6 +69,10 @@ func (x *Status) StableMarshal(buf []byte) []byte { } func (x *Status) StableSize() (size int) { + if x == nil { + return 0 + } + size += protoutil.UInt32Size(statusCodeFNum, CodeToGRPC(x.code)) size += protoutil.StringSize(statusMsgFNum, x.msg) diff --git a/util/proto/marshal.go b/util/proto/marshal.go index a82478b..ff0d30b 100644 --- a/util/proto/marshal.go +++ b/util/proto/marshal.go @@ -10,7 +10,6 @@ import ( "encoding/binary" "math" "math/bits" - "reflect" ) type ( @@ -303,14 +302,13 @@ func NestedStructurePrefix(field int64) (prefix uint64, ln int) { } func NestedStructureMarshal(field int64, buf []byte, v stableMarshaller) int { - if v == nil || reflect.ValueOf(v).IsNil() { + n := v.StableSize() + if n == 0 { return 0 } prefix, _ := NestedStructurePrefix(field) offset := binary.PutUvarint(buf, prefix) - - n := v.StableSize() offset += binary.PutUvarint(buf[offset:], uint64(n)) v.StableMarshal(buf[offset:]) @@ -318,12 +316,12 @@ func NestedStructureMarshal(field int64, buf []byte, v stableMarshaller) int { } func NestedStructureSize(field int64, v stableMarshaller) (size int) { - if v == nil || reflect.ValueOf(v).IsNil() { + n := v.StableSize() + if n == 0 { return 0 } _, ln := NestedStructurePrefix(field) - n := v.StableSize() size = ln + VarUIntSize(uint64(n)) + n return size