Skip to content

Commit

Permalink
Fixing a bug with JSON marshalling
Browse files Browse the repository at this point in the history
  • Loading branch information
wk8 committed Dec 9, 2022
1 parent 6b91e87 commit ea3e882
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 3 deletions.
5 changes: 4 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
# Changelog

# 2.1 - Dec 7th 2022
# 2.1.1 - Dec 9th 2022
* Fixing a bug with JSON marshalling

# 2.1.0 - Dec 7th 2022
* Added support for JSON serialization/deserialization
17 changes: 16 additions & 1 deletion json.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package orderedmap

import (
"bytes"
"encoding"
"encoding/json"
"fmt"
Expand Down Expand Up @@ -64,7 +65,21 @@ func (om *OrderedMap[K, V]) MarshalJSON() ([]byte, error) {

writer.RawByte('}')

return writer.Buffer.Buf, writer.Error
return dumpWriter(&writer)
}

func dumpWriter(writer *jwriter.Writer) ([]byte, error) {
if writer.Error != nil {
return nil, writer.Error
}

var buf bytes.Buffer
buf.Grow(writer.Size())
if _, err := writer.DumpTo(&buf); err != nil {
return nil, err
}

return buf.Bytes(), nil
}

// UnmarshalJSON implements the json.Unmarshaler interface.
Expand Down
3 changes: 2 additions & 1 deletion json_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,11 @@ func TestMarshalJSON(t *testing.T) {
om.Set(6, "100")
om.Set(8, "baz")
om.Set(8, "baz")
om.Set(9, "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque auctor augue accumsan mi maximus, quis viverra massa pretium. Phasellus imperdiet sapien a interdum sollicitudin. Duis at commodo lectus, a lacinia sem.")

b, err := json.Marshal(om)
assert.NoError(t, err)
assert.Equal(t, `{"1":"bar","7":"baz","2":28,"3":100,"4":"baz","5":"28","6":"100","8":"baz"}`, string(b))
assert.Equal(t, `{"1":"bar","7":"baz","2":28,"3":100,"4":"baz","5":"28","6":"100","8":"baz","9":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque auctor augue accumsan mi maximus, quis viverra massa pretium. Phasellus imperdiet sapien a interdum sollicitudin. Duis at commodo lectus, a lacinia sem."}`, string(b))
})

t.Run("string key", func(t *testing.T) {
Expand Down

0 comments on commit ea3e882

Please sign in to comment.