Skip to content

Commit

Permalink
Refactor merge functions in badjson
Browse files Browse the repository at this point in the history
Split the existing Merge function into two separate functions, "Merge" and "MergeFromJSON", to enhance readability and separation of concerns. Additionally, a new structure "TypedMessage" has been introduced to handle byte-to-JSON conversion.
  • Loading branch information
nekohasekai committed Dec 10, 2023
1 parent 7026a5d commit 0d90e9d
Showing 1 changed file with 25 additions and 21 deletions.
46 changes: 25 additions & 21 deletions common/json/badjson/merge.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,27 +8,6 @@ import (
"github.com/sagernet/sing/common/json"
)

func Merge[T any](source T, destination T) (T, error) {
rawSource, err := json.Marshal(source)
if err != nil {
return common.DefaultValue[T](), E.Cause(err, "marshal source")
}
rawDestination, err := json.Marshal(destination)
if err != nil {
return common.DefaultValue[T](), E.Cause(err, "marshal destination")
}
rawMerged, err := MergeJSON(rawSource, rawDestination)
if err != nil {
return common.DefaultValue[T](), E.Cause(err, "merge options")
}
var merged T
err = json.Unmarshal(rawMerged, &merged)
if err != nil {
return common.DefaultValue[T](), E.Cause(err, "unmarshal merged options")
}
return merged, nil
}

func Omitempty[T any](value T) (T, error) {
objectContent, err := json.Marshal(value)
if err != nil {
Expand All @@ -50,6 +29,31 @@ func Omitempty[T any](value T) (T, error) {
return newObject, nil
}

func Merge[T any](source T, destination T) (T, error) {
rawSource, err := json.Marshal(source)
if err != nil {
return common.DefaultValue[T](), E.Cause(err, "marshal source")
}
return MergeFromJSON(rawSource, destination)
}

func MergeFromJSON[T any](rawSource json.RawMessage, destination T) (T, error) {
rawDestination, err := json.Marshal(destination)
if err != nil {
return common.DefaultValue[T](), E.Cause(err, "marshal destination")
}
rawMerged, err := MergeJSON(rawSource, rawDestination)
if err != nil {
return common.DefaultValue[T](), E.Cause(err, "merge options")
}
var merged T
err = json.Unmarshal(rawMerged, &merged)
if err != nil {
return common.DefaultValue[T](), E.Cause(err, "unmarshal merged options")
}
return merged, nil
}

func MergeJSON(rawSource json.RawMessage, rawDestination json.RawMessage) (json.RawMessage, error) {
source, err := Decode(rawSource)
if err != nil {
Expand Down

0 comments on commit 0d90e9d

Please sign in to comment.