Skip to content

Commit

Permalink
feat: Add Json marshalling, unmarshalling
Browse files Browse the repository at this point in the history
  • Loading branch information
1eedaegon committed Apr 2, 2024
1 parent 25cf643 commit adc8889
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
34 changes: 34 additions & 0 deletions hashset.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package hashset

import (
"encoding/json"
"fmt"
"reflect"
"sync"
)
Expand Down Expand Up @@ -147,6 +149,38 @@ func (s *Set) ToSlice() []interface{} {
return uniTypeSlice
}

func (s *Set) MarshalJSON() ([]byte, error) {
stringMap := make(map[string]bool)
// s.mu.RLock()
for k, v := range s.hash {
if reflect.TypeOf(k).Kind() == reflect.Func {
fmt.Printf("[WARN] Skipped function pointer value in set: %v (hashset - MarshalJSON)", k)
continue
}
key := fmt.Sprintf("%v", k)
stringMap[key] = v
}
// s.mu.RUnlock()
jsonByte, err := json.Marshal(stringMap)
if err != nil {
return nil, err
}
return jsonByte, nil
}
func (s *Set) UnmarshalJSON(data []byte) error {
stringMap := make(map[string]bool)
// Here, it is guaranteed that Unmarshal will be appropriate.
s.mu.Lock()
if err := json.Unmarshal(data, &stringMap); err != nil {
return err
}
s.mu.Unlock()
for k := range stringMap {
s.Add(k)
}
return nil
}

// MakeComparable returns pointer(address) not comparable types: slice, map, function
func MakeComparable(element interface{}) interface{} {
/*
Expand Down
17 changes: 16 additions & 1 deletion hashset_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package hashset

import (
"encoding/json"
"reflect"
"strconv"
"sync"
Expand Down Expand Up @@ -127,16 +128,17 @@ func TestConvertToSet(t *testing.T) {
func TestConvertToSlice(t *testing.T) {
caseSlice := []int{1, 2, 3}
caseSliceTwo := []string{"1", "a", "b"}
// Splitting slices
s := New(caseSlice, caseSliceTwo)
require.Equal(t, 6, s.Len())
// Converting set to slice
arr := s.ToSlice()
require.Equal(t, 6, len(arr))
require.True(t, reflect.ValueOf(arr).Kind() == reflect.Slice)
require.Contains(t, arr, 1)
require.Contains(t, arr, 3)
require.Contains(t, arr, "1")
require.Contains(t, arr, "b")

}

func TestUnion(t *testing.T) {
Expand Down Expand Up @@ -170,6 +172,19 @@ func TestIntersection(t *testing.T) {
func TestDifference(t *testing.T) {}
func TestFunctionElement(t *testing.T) {}
func TestStructElement(t *testing.T) {}

func TestMarshalJSON(t *testing.T) {

caseSlice := []int{1, 2, 3}
caseSliceTwo := []string{"1", "a", "b"}
// Splitting slices
s := New(caseSlice, caseSliceTwo)
ms, err := json.Marshal(s)
require.NoError(t, err)
s2 := New()
err = json.Unmarshal(ms, s2)
require.NoError(t, err)
}
func TestConcurrentAddElement10Goroutine100000Loop(t *testing.T) {
var wg sync.WaitGroup
s := New()
Expand Down

0 comments on commit adc8889

Please sign in to comment.