1
16
17 package issue_test
18
19 import (
20 `encoding`
21 `encoding/json`
22 `strconv`
23 `testing`
24
25 `github.com/bytedance/sonic/encoder`
26 `github.com/stretchr/testify/require`
27 )
28
29 type ptrTextMarshaler string
30
31 func (k *ptrTextMarshaler) MarshalText() ([]byte, error) {
32 if k == nil {
33 return []byte("ptrisnil"), nil
34 }
35 return []byte("ptrto" + string(*k)), nil
36 }
37
38 type textMarshaler string
39
40 func (k textMarshaler) MarshalText() ([]byte, error) {
41 return []byte(string(k)), nil
42 }
43
44 func TestIssue115_MarshalMapWithSort(t *testing.T) {
45 nptext := (*ptrTextMarshaler)(nil)
46 ptext := ptrTextMarshaler("key")
47 text0 := textMarshaler("")
48 text1 := textMarshaler("1")
49 text2 := textMarshaler("2")
50 testCases := []struct {
51 v interface{}
52 want string
53 }{
54 { v: map[string]int{"b":2, "a":1, "c":3}, want: `{"a":1,"b":2,"c":3}`},
55 { v: map[int64]int{1:-1, -2:2, 0:0}, want: `{"-2":2,"0":0,"1":-1}`},
56 { v: map[uint]int{1:-1, ^uint(0):2, 0:0}, want: `{"0":0,"1":-1,"18446744073709551615":2}`},
57 { v: map[uintptr]int{uintptr(0xf):0xf, uintptr(0x0):0}, want: `{"0":0,"15":15}`},
58 { v: map[encoding.TextMarshaler]interface{}{
59 nptext : nil,
60 &ptext : struct{}{},
61 text0 : "",
62 &text1 : 1,
63 text2 : text2,
64 },
65 want: `{"":"","1":1,"2":"2","ptrisnil":null,"ptrtokey":{}}`,
66 },
67 }
68
69 for _, tt := range testCases {
70 out, err := encoder.Encode(tt.v, encoder.SortMapKeys)
71 require.NoError(t, err)
72 require.Equal(t, tt.want, string(out))
73 }
74 }
75
76 func TestIssue115_MarshalLargeIntKeyMapWitSort(t *testing.T) {
77 N := 10000
78 m := map[int]string{}
79 for i := 0; i < N; i++ {
80 a := strconv.Itoa(i)
81 m[i] = a
82 }
83
84 exp, err := json.Marshal(&m)
85 require.NoError(t, err)
86 got, err := encoder.Encode(&m, encoder.SortMapKeys)
87 require.NoError(t, err)
88 require.Equal(t, string(exp), string(got))
89 }
90
91
View as plain text