From 544e73116660c4c5d678609cdc970b774082f1a2 Mon Sep 17 00:00:00 2001 From: Masaaki Goshima Date: Wed, 2 Jun 2021 19:02:36 +0900 Subject: [PATCH] Fix value of totalLength for encoding --- encode_test.go | 19 +++++++++++++++++++ internal/encoder/opcode.go | 24 ++++++++++++++++++++++-- 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/encode_test.go b/encode_test.go index 9c4ce9a..b2e5ec4 100644 --- a/encode_test.go +++ b/encode_test.go @@ -1893,3 +1893,22 @@ func TestIssue180(t *testing.T) { t.Fatalf("failed to equal encoded result: expected %s but got %s", string(b1), string(b2)) } } + +func TestIssue235(t *testing.T) { + type TaskMessage struct { + Type string + Payload map[string]interface{} + UniqueKey string + } + msg := TaskMessage{ + Payload: map[string]interface{}{ + "sent_at": map[string]interface{}{ + "Time": "0001-01-01T00:00:00Z", + "Valid": false, + }, + }, + } + if _, err := json.Marshal(msg); err != nil { + t.Fatal(err) + } +} diff --git a/internal/encoder/opcode.go b/internal/encoder/opcode.go index 220d5f3..15a695d 100644 --- a/internal/encoder/opcode.go +++ b/internal/encoder/opcode.go @@ -49,6 +49,23 @@ type Opcode struct { DisplayKey string // key text to display } +func (c *Opcode) MaxIdx() uint32 { + max := uint32(0) + for _, value := range []uint32{ + c.Idx, + c.ElemIdx, + c.Length, + c.MapIter, + c.MapPos, + c.Size, + } { + if max < value { + max = value + } + } + return max +} + func (c *Opcode) ToHeaderType(isString bool) OpType { switch c.Op { case OpInt: @@ -338,7 +355,10 @@ func (c *Opcode) BeforeLastCode() *Opcode { func (c *Opcode) TotalLength() int { var idx int for code := c; code.Op != OpEnd; { - idx = int(code.Idx / uintptrSize) + maxIdx := int(code.MaxIdx() / uintptrSize) + if idx < maxIdx { + idx = maxIdx + } if code.Op == OpRecursiveEnd { break } @@ -349,7 +369,7 @@ func (c *Opcode) TotalLength() int { code = code.Next } } - return idx + 2 // opEnd + 1 + return idx + 1 } func (c *Opcode) decOpcodeIndex() {