badjson: Refactor and restructure Merge functions

The Merge function has been refactored for clearer code by splitting it into multiple functions: "Merge", "MergeFromSource", "MergeFromDestination" and "MergeFrom" in the badjson package. These new functions improve the handling of raw JSON during merge and with this refactoring, the responsibility of each function is more defined.
This commit is contained in:
世界 2023-12-10 23:02:37 +08:00
parent 36acc18bfb
commit 4c4773fe54
No known key found for this signature in database
GPG key ID: CD109927C34A63C4

View file

@ -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 {
@ -50,6 +29,47 @@ 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")
}
rawDestination, err := json.Marshal(destination)
if err != nil {
return common.DefaultValue[T](), E.Cause(err, "marshal destination")
}
return MergeFrom[T](rawSource, rawDestination)
}
func MergeFromSource[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")
}
return MergeFrom[T](rawSource, rawDestination)
}
func MergeFromDestination[T any](source T, rawDestination json.RawMessage) (T, error) {
rawSource, err := json.Marshal(source)
if err != nil {
return common.DefaultValue[T](), E.Cause(err, "marshal source")
}
return MergeFrom[T](rawSource, rawDestination)
}
func MergeFrom[T any](rawSource json.RawMessage, rawDestination json.RawMessage) (T, error) {
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 {