From d650250f329e0864e610ccb61395ca3cf8a617e8 Mon Sep 17 00:00:00 2001 From: aviadl Date: Wed, 16 Feb 2022 12:02:45 +0200 Subject: [PATCH] Fix unmarshaling an empty time struct when an interface is supplied to unmarshal command When a time.Time struct is supplied, the decode function goes in another path, and the UTC timezone is set on the empty time object Added this now to the path when an interface is supplied --- msgpack_test.go | 27 +++++++++++++++++++++++++++ time.go | 5 +++++ 2 files changed, 32 insertions(+) diff --git a/msgpack_test.go b/msgpack_test.go index 1b77027..ce30fa2 100644 --- a/msgpack_test.go +++ b/msgpack_test.go @@ -247,6 +247,33 @@ func TestEmbedding(t *testing.T) { } } +func TestEmptyTimeMarshalWithInterface(t *testing.T) { + a := time.Time{} + b, err := msgpack.Marshal(a) + if err != nil { + t.Fatal(err) + } + var out interface{} + err = msgpack.Unmarshal(b, &out) + if err != nil { + t.Fatal(err) + } + name, _ := out.(time.Time).Zone() + if name != "UTC" { + t.Fatal("Got wrong timezone") + } + + var out2 time.Time + err = msgpack.Unmarshal(b, &out2) + if err != nil { + t.Fatal(err) + } + name, _ = out2.Zone() + if name != "UTC" { + t.Fatal("Got wrong timezone") + } +} + func (t *MsgpackTest) TestSliceNil() { in := [][]*int{nil} var out [][]*int diff --git a/time.go b/time.go index 37cc432..1a4ba12 100644 --- a/time.go +++ b/time.go @@ -26,6 +26,11 @@ func timeDecoder(d *Decoder, v reflect.Value, extLen int) error { return err } + if tm.IsZero() { + // Zero time does not have timezone information. + tm = tm.UTC() + } + ptr := v.Addr().Interface().(*time.Time) *ptr = tm