forked from vmihailenco/msgpack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmsgpack_test.go
More file actions
820 lines (690 loc) · 19 KB
/
Copy pathmsgpack_test.go
File metadata and controls
820 lines (690 loc) · 19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
package msgpack_test
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"math"
"reflect"
"runtime"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"github.com/Basekick-Labs/msgpack/v6"
)
type nameStruct struct {
Name string
}
type MsgpackTest struct {
suite.Suite
buf *bytes.Buffer
enc *msgpack.Encoder
dec *msgpack.Decoder
}
func (t *MsgpackTest) SetupTest() {
t.buf = &bytes.Buffer{}
t.enc = msgpack.NewEncoder(t.buf)
t.dec = msgpack.NewDecoder(bufio.NewReader(t.buf))
}
func TestMsgpackTestSuite(t *testing.T) {
suite.Run(t, new(MsgpackTest))
}
func (t *MsgpackTest) TestDecodeNil() {
t.NotNil(t.dec.Decode(nil))
}
func (t *MsgpackTest) TestTime() {
in := time.Now()
var out time.Time
t.Nil(t.enc.Encode(in))
t.Nil(t.dec.Decode(&out))
t.True(out.Equal(in))
var zero time.Time
t.Nil(t.enc.Encode(zero))
t.Nil(t.dec.Decode(&out))
t.True(out.Equal(zero))
t.True(out.IsZero())
}
func (t *MsgpackTest) TestLargeBytes() {
N := int(1e6)
src := bytes.Repeat([]byte{'1'}, N)
t.Nil(t.enc.Encode(src))
var dst []byte
t.Nil(t.dec.Decode(&dst))
t.Equal(dst, src)
}
func (t *MsgpackTest) TestLargeString() {
N := int(1e6)
src := string(bytes.Repeat([]byte{'1'}, N))
t.Nil(t.enc.Encode(src))
var dst string
t.Nil(t.dec.Decode(&dst))
t.Equal(dst, src)
}
func (t *MsgpackTest) TestDecodeUntypedMapHugeDeclaredLen() {
// A map32 header declaring ~2G entries with no payload: the map size
// hint must be clamped at maxMapSize before allocation (with the old
// code this allocated a multi-GB map upfront), then fail decoding the
// first key.
//
// 0x7fffffff rather than 0xffffffff: the latter is now rejected by the
// int-overflow check on 32-bit builds before reaching the clamp, so it
// would pass for the wrong reason. This value fits in an int on every
// platform and exercises the clamp itself.
data := []byte{0xdf, 0x7f, 0xff, 0xff, 0xff}
var before, after runtime.MemStats
runtime.GC()
runtime.ReadMemStats(&before)
dec := msgpack.NewDecoder(bytes.NewReader(data))
_, err := dec.DecodeUntypedMap()
t.NotNil(err)
runtime.ReadMemStats(&after)
// The clamp caps the hint at maxMapSize (1M entries). Without it the
// declared ~2G entries are allocated upfront -- hundreds of MB and tens
// of seconds. Allow generous headroom while still failing loudly if the
// clamp is removed.
if alloc := after.TotalAlloc - before.TotalAlloc; alloc > 256<<20 {
t.Failf("allocation not clamped", "decode allocated %d MiB, want < 256 MiB", alloc>>20)
}
}
func (t *MsgpackTest) TestDecodeUntypedMap() {
in := map[interface{}]interface{}{int8(1): "one", "two": int8(2)}
t.Nil(t.enc.Encode(in))
out, err := t.dec.DecodeUntypedMap()
t.Nil(err)
t.Equal(in, out)
}
func (t *MsgpackTest) TestDecodeBytesHugeDeclaredLen() {
// A bin32 header declaring ~2GB with a 1-byte payload must fail with a
// read error after at most one bytesAllocLimit-sized chunk — not attempt
// to allocate the full declared length upfront.
//
// 0x7fffffff rather than 0xffffffff: on 32-bit builds the latter exceeds
// math.MaxInt and is rejected by the length-overflow check before the
// chunked read is reached, so it would fail with a different error.
// This value fits in an int on every platform.
data := []byte{0xc6, 0x7f, 0xff, 0xff, 0xff, 'x'}
var out []byte
dec := msgpack.NewDecoder(bytes.NewReader(data))
t.True(errors.Is(dec.Decode(&out), io.ErrUnexpectedEOF))
// Same via DecodeBytes (d.bytes path).
dec = msgpack.NewDecoder(bytes.NewReader(data))
_, err := dec.DecodeBytes()
t.True(errors.Is(err, io.ErrUnexpectedEOF))
// And via a []byte struct field (decodeBytesValue path).
var s struct{ Data []byte }
payload := append([]byte{0x81, 0xa4, 'D', 'a', 't', 'a'}, data...)
dec = msgpack.NewDecoder(bytes.NewReader(payload))
t.True(errors.Is(dec.Decode(&s), io.ErrUnexpectedEOF))
}
func (t *MsgpackTest) TestUnmarshalBytesHugeDeclaredLen() {
// On the byte-slice path the declared length is validated against the
// remaining input before allocating: must fail fast, no huge alloc.
// 0x7fffffff for the same reason as TestDecodeBytesHugeDeclaredLen.
data := []byte{0xc6, 0x7f, 0xff, 0xff, 0xff, 'x'}
var out []byte
t.True(errors.Is(msgpack.Unmarshal(data, &out), io.ErrUnexpectedEOF))
}
func (t *MsgpackTest) TestUnmarshalBytesLarge() {
src := bytes.Repeat([]byte{'x'}, 2500*1024)
data, err := msgpack.Marshal(src)
t.Nil(err)
var dst []byte
t.Nil(msgpack.Unmarshal(data, &dst))
t.Equal(src, dst)
// The result must be caller-owned, not an alias of the input buffer.
data[len(data)-1] = 'y'
t.Equal(byte('x'), dst[len(dst)-1])
}
func (t *MsgpackTest) TestDecodeBytesLargeStream() {
// Larger than bytesAllocLimit (1MB) so the chunked grow path is hit.
src := bytes.Repeat([]byte{'x'}, 2500*1024)
data, err := msgpack.Marshal(src)
t.Nil(err)
var dst []byte
dec := msgpack.NewDecoder(bytes.NewReader(data))
t.Nil(dec.Decode(&dst))
t.Equal(src, dst)
// DisableAllocLimit path still works.
dst = nil
dec = msgpack.NewDecoder(bytes.NewReader(data))
dec.DisableAllocLimit(true)
t.Nil(dec.Decode(&dst))
t.Equal(src, dst)
}
func (t *MsgpackTest) TestSliceOfStructs() {
in := []*nameStruct{{"hello"}}
var out []*nameStruct
t.Nil(t.enc.Encode(in))
t.Nil(t.dec.Decode(&out))
t.Equal(out, in)
}
func (t *MsgpackTest) TestMap() {
for _, i := range []struct {
m map[string]string
b []byte
}{
{map[string]string{}, []byte{0x80}},
{map[string]string{"hello": "world"}, []byte{0x81, 0xa5, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0xa5, 0x77, 0x6f, 0x72, 0x6c, 0x64}},
} {
t.Nil(t.enc.Encode(i.m))
t.Equal(t.buf.Bytes(), i.b, fmt.Errorf("err encoding %v", i.m))
var m map[string]string
t.Nil(t.dec.Decode(&m))
t.Equal(m, i.m)
}
}
func (t *MsgpackTest) TestEncodeTypeSwitchFastPaths() {
// Every type fast-pathed in Encode() must produce output byte-identical
// to the reflection path (EncodeValue).
for _, v := range []interface{}{
int8(-42), int8(127), int8(-128),
int16(-3200), int16(32767),
int32(-320000), int32(2147483647),
uint8(0), uint8(200), uint8(255),
uint16(64000),
uint32(4000000000),
[]string{"hello", "world"},
[]string{},
[]string(nil),
map[string]bool{"hello": true},
map[string]bool{},
map[string]bool(nil),
} {
var fast, slow bytes.Buffer
enc := msgpack.NewEncoder(&fast)
t.Nil(enc.Encode(v))
enc = msgpack.NewEncoder(&slow)
t.Nil(enc.EncodeValue(reflect.ValueOf(v)))
t.Equal(slow.Bytes(), fast.Bytes(), fmt.Sprintf("encoding %T(%v)", v, v))
}
}
func (t *MsgpackTest) TestEncodeMapStringBoolSorted() {
in := map[string]bool{"c": true, "a": false, "b": true}
t.enc.SetSortMapKeys(true)
t.Nil(t.enc.Encode(in))
t.Equal([]byte{
0x83,
0xa1, 'a', 0xc2,
0xa1, 'b', 0xc3,
0xa1, 'c', 0xc3,
}, t.buf.Bytes())
var out map[string]bool
t.Nil(t.dec.Decode(&out))
t.Equal(in, out)
}
func (t *MsgpackTest) TestMapStringInterfaceReuse() {
in := map[string]interface{}{"hello": "world", "n": int8(1)}
t.Nil(t.enc.Encode(in))
// A caller-supplied map is decoded into in place (entries merged),
// matching the map[string]string behavior.
dst := map[string]interface{}{"existing": true, "hello": "stale"}
t.Nil(t.dec.Decode(&dst))
t.Equal(map[string]interface{}{
"existing": true, // retained
"hello": "world",
"n": int8(1),
}, dst)
// msgpack nil still resets the destination to nil.
t.Nil(t.enc.Encode(map[string]interface{}(nil)))
t.Nil(t.dec.Decode(&dst))
t.Nil(dst)
// And a nil destination map is allocated as before.
t.Nil(t.enc.Encode(in))
dst = nil
t.Nil(t.dec.Decode(&dst))
t.Equal(in, dst)
// An empty msgpack map leaves a pre-populated destination untouched.
t.Nil(t.enc.Encode(map[string]interface{}{}))
dst = map[string]interface{}{"existing": true}
t.Nil(t.dec.Decode(&dst))
t.Equal(map[string]interface{}{"existing": true}, dst)
}
func (t *MsgpackTest) TestMapStringInterfaceStructFieldReuse() {
// Struct fields of type map[string]interface{} get the same merge
// semantics as map[string]string fields always had: a pre-populated
// field map is decoded into, not replaced.
type withMap struct {
Data map[string]interface{}
}
t.Nil(t.enc.Encode(withMap{Data: map[string]interface{}{"new": "value"}}))
out := withMap{Data: map[string]interface{}{"existing": true}}
t.Nil(t.dec.Decode(&out))
t.Equal(map[string]interface{}{"existing": true, "new": "value"}, out.Data)
}
func (t *MsgpackTest) TestStructNil() {
var dst *nameStruct
t.Nil(t.enc.Encode(nameStruct{Name: "foo"}))
t.Nil(t.dec.Decode(&dst))
t.NotNil(dst)
t.Equal(dst.Name, "foo")
}
func (t *MsgpackTest) TestStructUnknownField() {
in := struct {
Field1 string
Field2 string
Field3 string
}{
Field1: "value1",
Field2: "value2",
Field3: "value3",
}
t.Nil(t.enc.Encode(in))
out := struct {
Field2 string
}{}
t.Nil(t.dec.Decode(&out))
t.Equal(out.Field2, "value2")
}
//------------------------------------------------------------------------------
type coderStruct struct {
name string
}
type wrapperStruct struct {
coderStruct
}
var (
_ msgpack.CustomEncoder = (*coderStruct)(nil)
_ msgpack.CustomDecoder = (*coderStruct)(nil)
)
func (s *coderStruct) Name() string {
return s.name
}
func (s *coderStruct) EncodeMsgpack(enc *msgpack.Encoder) error {
return enc.Encode(s.name)
}
func (s *coderStruct) DecodeMsgpack(dec *msgpack.Decoder) error {
return dec.Decode(&s.name)
}
func (t *MsgpackTest) TestCoder() {
in := &coderStruct{name: "hello"}
var out coderStruct
t.Nil(t.enc.Encode(in))
t.Nil(t.dec.Decode(&out))
t.Equal(out.Name(), "hello")
}
func (t *MsgpackTest) TestNilCoder() {
in := &coderStruct{name: "hello"}
var out *coderStruct
t.Nil(t.enc.Encode(in))
t.Nil(t.dec.Decode(&out))
t.Equal(out.Name(), "hello")
}
func (t *MsgpackTest) TestNilCoderValue() {
in := &coderStruct{name: "hello"}
var out *coderStruct
t.Nil(t.enc.Encode(in))
t.Nil(t.dec.DecodeValue(reflect.ValueOf(&out)))
t.Equal(out.Name(), "hello")
}
func (t *MsgpackTest) TestPtrToCoder() {
in := &coderStruct{name: "hello"}
var out coderStruct
out2 := &out
t.Nil(t.enc.Encode(in))
t.Nil(t.dec.Decode(&out2))
t.Equal(out.Name(), "hello")
}
func (t *MsgpackTest) TestWrappedCoder() {
in := &wrapperStruct{coderStruct: coderStruct{name: "hello"}}
var out wrapperStruct
t.Nil(t.enc.Encode(in))
t.Nil(t.dec.Decode(&out))
t.Equal(out.Name(), "hello")
}
//------------------------------------------------------------------------------
type struct2 struct {
Name string
}
type struct1 struct {
Name string
Struct2 struct2
}
func (t *MsgpackTest) TestNestedStructs() {
in := &struct1{Name: "hello", Struct2: struct2{Name: "world"}}
var out struct1
t.Nil(t.enc.Encode(in))
t.Nil(t.dec.Decode(&out))
t.Equal(out.Name, in.Name)
t.Equal(out.Struct2.Name, in.Struct2.Name)
}
type Struct4 struct {
Name2 string
}
type Struct3 struct {
Struct4
Name1 string
}
func TestEmbedding(t *testing.T) {
in := &Struct3{
Name1: "hello",
Struct4: Struct4{
Name2: "world",
},
}
var out Struct3
b, err := msgpack.Marshal(in)
if err != nil {
t.Fatal(err)
}
err = msgpack.Unmarshal(b, &out)
if err != nil {
t.Fatal(err)
}
if out.Name1 != in.Name1 {
t.Fatalf("")
}
if out.Name2 != in.Name2 {
t.Fatalf("")
}
}
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
t.Nil(t.enc.Encode(in))
t.Nil(t.dec.Decode(&out))
t.Equal(out, in)
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
func TestNoPanicOnUnsupportedKey(t *testing.T) {
data := []byte{0x81, 0x81, 0xa1, 0x78, 0xc3, 0xc3}
_, err := msgpack.NewDecoder(bytes.NewReader(data)).DecodeTypedMap()
require.EqualError(t, err, "msgpack: unsupported map key: map[string]interface {}")
}
func TestMapDefault(t *testing.T) {
in := map[string]interface{}{
"foo": "bar",
"hello": map[string]interface{}{
"foo": "bar",
},
}
b, err := msgpack.Marshal(in)
require.Nil(t, err)
var out map[string]interface{}
err = msgpack.Unmarshal(b, &out)
require.Nil(t, err)
require.Equal(t, in, out)
}
func TestRawMessage(t *testing.T) {
type In struct {
Foo map[string]interface{}
}
type Out struct {
Foo msgpack.RawMessage
}
type Out2 struct {
Foo interface{}
}
b, err := msgpack.Marshal(&In{
Foo: map[string]interface{}{
"hello": "world",
},
})
require.Nil(t, err)
var out Out
err = msgpack.Unmarshal(b, &out)
require.Nil(t, err)
var m map[string]string
err = msgpack.Unmarshal(out.Foo, &m)
require.Nil(t, err)
require.Equal(t, map[string]string{
"hello": "world",
}, m)
msg := new(msgpack.RawMessage)
out2 := Out2{
Foo: msg,
}
err = msgpack.Unmarshal(b, &out2)
require.Nil(t, err)
require.Equal(t, out.Foo, *msg)
}
func TestInterface(t *testing.T) {
type Interface struct {
Foo interface{}
}
in := Interface{Foo: "foo"}
b, err := msgpack.Marshal(in)
require.Nil(t, err)
var str string
out := Interface{Foo: &str}
err = msgpack.Unmarshal(b, &out)
require.Nil(t, err)
require.Equal(t, "foo", str)
}
func TestNaN(t *testing.T) {
in := float64(math.NaN())
b, err := msgpack.Marshal(in)
require.Nil(t, err)
var out float64
err = msgpack.Unmarshal(b, &out)
require.Nil(t, err)
require.True(t, math.IsNaN(out))
}
func TestSetSortMapKeys(t *testing.T) {
in := map[string]interface{}{
"a": "a",
"b": "b",
"c": "c",
"d": "d",
}
var buf bytes.Buffer
enc := msgpack.NewEncoder(&buf)
enc.SetSortMapKeys(true)
dec := msgpack.NewDecoder(&buf)
err := enc.Encode(in)
require.Nil(t, err)
wanted := make([]byte, buf.Len())
copy(wanted, buf.Bytes())
buf.Reset()
for i := 0; i < 100; i++ {
err := enc.Encode(in)
require.Nil(t, err)
require.Equal(t, wanted, buf.Bytes())
out, err := dec.DecodeMap()
require.Nil(t, err)
require.Equal(t, in, out)
}
}
func TestSetOmitEmpty(t *testing.T) {
var buf bytes.Buffer
enc := msgpack.NewEncoder(&buf)
enc.SetOmitEmpty(true)
err := enc.Encode(EmbeddingPtrTest{})
require.Nil(t, err)
var t2 *EmbeddingPtrTest
dec := msgpack.NewDecoder(&buf)
err = dec.Decode(&t2)
require.Nil(t, err)
require.Nil(t, t2.Exported)
type Nested struct {
Foo string
Bar string
}
type Item struct {
X Nested
Y *Nested
}
i := Item{}
buf.Reset()
err = enc.Encode(i)
require.Nil(t, err)
require.NotContains(t, buf.Bytes(), byte('X'))
require.NotContains(t, buf.Bytes(), byte('Y'))
i = Item{Y: &Nested{}}
buf.Reset()
err = enc.Encode(i)
require.Nil(t, err)
require.NotContains(t, buf.Bytes(), byte('X'))
require.Contains(t, buf.Bytes(), byte('Y'))
}
type NullInt struct {
Valid bool
Int int
}
func (i *NullInt) Set(j int) {
i.Int = j
i.Valid = true
}
func (i NullInt) IsZero() bool {
return !i.Valid
}
func (i NullInt) MarshalMsgpack() ([]byte, error) {
return msgpack.Marshal(i.Int)
}
func (i *NullInt) UnmarshalMsgpack(b []byte) error {
if err := msgpack.Unmarshal(b, &i.Int); err != nil {
return err
}
i.Valid = true
return nil
}
type Secretive struct {
Visible bool
hidden bool
}
type T struct {
I NullInt `msgpack:",omitempty"`
J NullInt
// Secretive is not a "simple" struct because it has an hidden field.
S Secretive `msgpack:",omitempty"`
}
func ExampleMarshal_ignore_simple_zero_structs_when_tagged_with_omitempty() {
var t1 T
raw, err := msgpack.Marshal(t1)
if err != nil {
panic(err)
}
var t2 T
if err = msgpack.Unmarshal(raw, &t2); err != nil {
panic(err)
}
fmt.Printf("%#v\n", t2)
t2.I.Set(42)
t2.S.hidden = true // won't be included because it is a hidden field
raw, err = msgpack.Marshal(t2)
if err != nil {
panic(err)
}
var t3 T
if err = msgpack.Unmarshal(raw, &t3); err != nil {
panic(err)
}
fmt.Printf("%#v\n", t3)
// Output: msgpack_test.T{I:msgpack_test.NullInt{Valid:false, Int:0}, J:msgpack_test.NullInt{Valid:true, Int:0}, S:msgpack_test.Secretive{Visible:false, hidden:false}}
// msgpack_test.T{I:msgpack_test.NullInt{Valid:true, Int:42}, J:msgpack_test.NullInt{Valid:true, Int:0}, S:msgpack_test.Secretive{Visible:false, hidden:false}}
}
type (
Value interface{}
Wrapper struct {
Value Value `msgpack:"v,omitempty"`
}
)
func TestEncodeWrappedValue(t *testing.T) {
v := (*time.Time)(nil)
c := &Wrapper{
Value: v,
}
var buf bytes.Buffer
require.Nil(t, msgpack.NewEncoder(&buf).Encode(v))
require.Nil(t, msgpack.NewEncoder(&buf).Encode(c))
}
func TestPtrValueDecode(t *testing.T) {
type Foo struct {
Bar *int
}
b, err := msgpack.Marshal(Foo{})
require.Nil(t, err)
bar1 := 123
foo := Foo{Bar: &bar1}
err = msgpack.Unmarshal(b, &foo)
require.Nil(t, err)
require.Nil(t, foo.Bar)
bar2 := 456
b, err = msgpack.Marshal(Foo{Bar: &bar2})
require.Nil(t, err)
err = msgpack.Unmarshal(b, &foo)
require.Nil(t, err)
require.NotNil(t, foo.Bar)
require.Equal(t, *foo.Bar, bar2)
}
// TestDecodeTypedMapSliceValuesAreIndependent is the regression test for #65.
// decodeTypedMapValue hoists the key/value reflect.Value slots out of the
// per-entry loop and zeroes them each iteration. Without the zeroing step,
// decodeSliceValue would reuse the previous iteration's backing array
// (since it reuses capacity when v.Cap() >= n), corrupting entries already
// written to the map.
func TestDecodeTypedMapSliceValuesAreIndependent(t *testing.T) {
in := map[int][]int{
1: {10, 11, 12},
2: {20, 21, 22},
3: {30, 31, 32},
}
b, err := msgpack.Marshal(in)
require.Nil(t, err)
var out map[int][]int
require.Nil(t, msgpack.Unmarshal(b, &out))
require.Equal(t, in, out)
// Mutating one entry must not touch any other. If the decode loop
// reused a single backing array, the entries would alias and this
// assertion would fail.
for i := range out[1] {
out[1][i] = -1
}
require.Equal(t, []int{20, 21, 22}, out[2])
require.Equal(t, []int{30, 31, 32}, out[3])
}
// TestDecodeTypedMapStructValuesAreIndependent covers the struct-value
// case of the same hoist bug. The struct carries a slice field so the
// aliasing mechanism fires through the hoisted value slot: decodeStructValue
// writes every field present in the payload, but the slice field itself is
// decoded via decodeSliceValue, which reuses the existing backing array
// when capacity is sufficient. Without per-iteration zeroing of the outer
// struct's slot, iteration 2's slice field would overwrite iteration 1's.
func TestDecodeTypedMapStructValuesAreIndependent(t *testing.T) {
type kv struct {
A int
B []string
}
in := map[int]kv{
1: {1, []string{"one", "uno"}},
2: {2, []string{"two", "dos"}},
3: {3, []string{"three", "tres"}},
}
b, err := msgpack.Marshal(in)
require.Nil(t, err)
var out map[int]kv
require.Nil(t, msgpack.Unmarshal(b, &out))
require.Equal(t, in, out)
for i := range out[1].B {
out[1].B[i] = "MUTATED"
}
require.Equal(t, []string{"two", "dos"}, out[2].B)
require.Equal(t, []string{"three", "tres"}, out[3].B)
}