diff --git a/encoder/compiler.go b/encoder/compiler.go index 89d9430..8f33482 100644 --- a/encoder/compiler.go +++ b/encoder/compiler.go @@ -529,7 +529,7 @@ func (self *_Compiler) compileMapBody(p *_Program, sp int, vt reflect.Type) { p.pin(v) p.int(_OP_byte, ':') p.add(_OP_map_value_next) - self.compileOne(p, sp + 1, vt.Elem(), false) + self.compileOne(p, sp + 2, vt.Elem(), false) p.int(_OP_goto, j) p.pin(i) p.pin(j) diff --git a/encoder/mapiter.go b/encoder/mapiter.go index 262de06..583964d 100644 --- a/encoder/mapiter.go +++ b/encoder/mapiter.go @@ -158,9 +158,8 @@ func iteratorStart(t *rt.GoMapType, m *rt.GoMap, fv uint64) (*_MapIterator, erro it := newIterator() mapiterinit(t, m, &it.it) - /* check for key-sorting - * empty map or map with only 1 item don't need sorting */ - if m.Count <= 1 || (fv & uint64(SortMapKeys)) == 0 { + /* check for key-sorting, empty map don't need sorting */ + if m.Count == 0 || (fv & uint64(SortMapKeys)) == 0 { it.ki = -1 return it, nil } @@ -178,9 +177,10 @@ func iteratorStart(t *rt.GoMapType, m *rt.GoMap, fv uint64) (*_MapIterator, erro } } - /* sort the keys */ - it.ki = 1 - radixQsort(it.data(), 0, maxDepth(it.kv.Len)) + /* sort the keys, map with only 1 item don't need sorting */ + if it.ki = 1; m.Count > 1 { + radixQsort(it.data(), 0, maxDepth(it.kv.Len)) + } /* load the first pair into iterator */ it.it.V = it.at(0).v diff --git a/issue98_test.go b/issue98_test.go new file mode 100644 index 0000000..1a58984 --- /dev/null +++ b/issue98_test.go @@ -0,0 +1,30 @@ +/* + * Copyright 2021 ByteDance Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package sonic + +import ( + `testing` + + `github.com/bytedance/sonic/encoder` + `github.com/stretchr/testify/require` +) + +func TestIssue98_SingleElementMapWithKeySorting(t *testing.T) { + v, err := encoder.Encode(map[int64]bool{1234: true}, encoder.SortMapKeys) + require.NoError(t, err) + require.Equal(t, `{"1234":true}`, string(v)) +}