Skip to content

Commit

Permalink
badjson: Improve omitempty
Browse files Browse the repository at this point in the history
  • Loading branch information
nekohasekai committed Mar 5, 2024
1 parent 88b8b92 commit c4c4f45
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 2 deletions.
13 changes: 13 additions & 0 deletions common/json/badjson/array.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,25 @@ package badjson
import (
"bytes"

"github.com/sagernet/sing/common"
E "github.com/sagernet/sing/common/exceptions"
"github.com/sagernet/sing/common/json"
)

type JSONArray []any

func (a JSONArray) IsEmpty() bool {
if len(a) == 0 {
return true
}
return common.All(a, func(it any) bool {
if valueInterface, valueMaybeEmpty := it.(isEmpty); valueMaybeEmpty && valueInterface.IsEmpty() {
return true
}
return false
})
}

func (a JSONArray) MarshalJSON() ([]byte, error) {
return json.Marshal([]any(a))
}
Expand Down
5 changes: 5 additions & 0 deletions common/json/badjson/empty.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package badjson

type isEmpty interface {
IsEmpty() bool
}
16 changes: 14 additions & 2 deletions common/json/badjson/object.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,23 @@ type JSONObject struct {
linkedhashmap.Map[string, any]
}

func (m JSONObject) MarshalJSON() ([]byte, error) {
func (m *JSONObject) IsEmpty() bool {
if m.Size() == 0 {
return true
}
return common.All(m.Entries(), func(it collections.MapEntry[string, any]) bool {
if valueInterface, valueMaybeEmpty := it.Value.(isEmpty); valueMaybeEmpty && valueInterface.IsEmpty() {
return true
}
return false
})
}

func (m *JSONObject) MarshalJSON() ([]byte, error) {
buffer := new(bytes.Buffer)
buffer.WriteString("{")
items := common.Filter(m.Entries(), func(it collections.MapEntry[string, any]) bool {
if valueObject, valueIsJSONObject := it.Value.(*JSONObject); valueIsJSONObject && valueObject.IsEmpty() {
if valueInterface, valueMaybeEmpty := it.Value.(isEmpty); valueMaybeEmpty && valueInterface.IsEmpty() {
return false
}
return true
Expand Down

0 comments on commit c4c4f45

Please sign in to comment.