Skip to content

Commit

Permalink
fix: Deserialize using a generic approach. (#121)
Browse files Browse the repository at this point in the history
  • Loading branch information
fujie-xiyou authored Aug 2, 2023
1 parent 6ea1fbe commit b20691d
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 17 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,4 @@ _cgo_export.*
_testmain.go

*.exe
.idea
12 changes: 11 additions & 1 deletion threadsafe_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -540,7 +540,17 @@ func Test_UnmarshalJSON(t *testing.T) {
t.Errorf("Expected no difference, got: %v", expected.Difference(actual))
}
}

func TestThreadUnsafeSet_UnmarshalJSON(t *testing.T) {
expected := NewThreadUnsafeSet[int64](1, 2, 3)
actual := NewThreadUnsafeSet[int64]()
err := actual.UnmarshalJSON([]byte(`[1, 2, 3]`))
if err != nil {
t.Errorf("Error should be nil: %v", err)
}
if !expected.Equal(actual) {
t.Errorf("Expected no difference, got: %v", expected.Difference(actual))
}
}
func Test_MarshalJSON(t *testing.T) {
expected := NewSet(
[]string{
Expand Down
19 changes: 3 additions & 16 deletions threadunsafe.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ SOFTWARE.
package mapset

import (
"bytes"
"encoding/json"
"fmt"
"strings"
Expand Down Expand Up @@ -311,24 +310,12 @@ func (s threadUnsafeSet[T]) MarshalJSON() ([]byte, error) {
// UnmarshalJSON recreates a set from a JSON array, it only decodes
// primitive types. Numbers are decoded as json.Number.
func (s threadUnsafeSet[T]) UnmarshalJSON(b []byte) error {
var i []any

d := json.NewDecoder(bytes.NewReader(b))
d.UseNumber()
err := d.Decode(&i)
var i []T
err := json.Unmarshal(b, &i)
if err != nil {
return err
}

for _, v := range i {
switch t := v.(type) {
case T:
s.add(t)
default:
// anything else must be skipped.
continue
}
}
s.Append(i...)

return nil
}

0 comments on commit b20691d

Please sign in to comment.