2022-07-02 17:57:04 +00:00
|
|
|
package option
|
|
|
|
|
|
|
|
import (
|
2022-07-03 15:23:18 +00:00
|
|
|
"github.com/sagernet/sing/common"
|
|
|
|
E "github.com/sagernet/sing/common/exceptions"
|
2023-12-01 12:15:11 +00:00
|
|
|
"github.com/sagernet/sing/common/json"
|
|
|
|
"github.com/sagernet/sing/common/json/badjson"
|
2022-07-02 17:57:04 +00:00
|
|
|
)
|
|
|
|
|
2022-07-03 11:43:27 +00:00
|
|
|
func ToMap(v any) (*badjson.JSONObject, error) {
|
2022-07-03 03:28:15 +00:00
|
|
|
inputContent, err := json.Marshal(v)
|
2022-07-02 17:57:04 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2022-07-03 11:43:27 +00:00
|
|
|
var content badjson.JSONObject
|
2022-07-03 03:28:15 +00:00
|
|
|
err = content.UnmarshalJSON(inputContent)
|
2022-07-02 17:57:04 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2022-07-02 19:42:57 +00:00
|
|
|
return &content, nil
|
2022-07-02 17:57:04 +00:00
|
|
|
}
|
|
|
|
|
2022-07-03 11:43:27 +00:00
|
|
|
func MergeObjects(objects ...any) (*badjson.JSONObject, error) {
|
|
|
|
var content badjson.JSONObject
|
2022-07-02 17:57:04 +00:00
|
|
|
for _, object := range objects {
|
|
|
|
objectMap, err := ToMap(object)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2022-07-02 19:42:57 +00:00
|
|
|
content.PutAll(objectMap)
|
2022-07-02 17:57:04 +00:00
|
|
|
}
|
2022-07-02 19:42:57 +00:00
|
|
|
return &content, nil
|
2022-07-02 17:57:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func MarshallObjects(objects ...any) ([]byte, error) {
|
2022-07-26 05:53:25 +00:00
|
|
|
objects = common.FilterNotNil(objects)
|
2022-07-03 15:23:18 +00:00
|
|
|
if len(objects) == 1 {
|
|
|
|
return json.Marshal(objects[0])
|
|
|
|
}
|
2022-07-02 17:57:04 +00:00
|
|
|
content, err := MergeObjects(objects...)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2022-07-03 03:28:15 +00:00
|
|
|
return content.MarshalJSON()
|
|
|
|
}
|
|
|
|
|
|
|
|
func UnmarshallExcluded(inputContent []byte, parentObject any, object any) error {
|
|
|
|
parentContent, err := ToMap(parentObject)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-07-03 11:43:27 +00:00
|
|
|
var content badjson.JSONObject
|
2022-07-03 03:28:15 +00:00
|
|
|
err = content.UnmarshalJSON(inputContent)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-07-03 11:43:27 +00:00
|
|
|
for _, key := range parentContent.Keys() {
|
|
|
|
content.Remove(key)
|
|
|
|
}
|
2022-07-03 15:23:18 +00:00
|
|
|
if object == nil {
|
|
|
|
if content.IsEmpty() {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return E.New("unexpected key: ", content.Keys()[0])
|
|
|
|
}
|
2022-07-03 03:28:15 +00:00
|
|
|
inputContent, err = content.MarshalJSON()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2024-07-22 04:10:22 +00:00
|
|
|
return json.UnmarshalDisallowUnknownFields(inputContent, object)
|
2022-07-02 17:57:04 +00:00
|
|
|
}
|