2022-07-02 17:57:04 +00:00
|
|
|
package option
|
|
|
|
|
|
|
|
import (
|
2022-07-03 03:28:15 +00:00
|
|
|
"bytes"
|
2022-07-02 19:42:57 +00:00
|
|
|
|
2022-07-03 03:28:15 +00:00
|
|
|
"github.com/goccy/go-json"
|
|
|
|
"github.com/sagernet/sing-box/common/linkedhashmap"
|
2022-07-02 17:57:04 +00:00
|
|
|
)
|
|
|
|
|
2022-07-02 19:42:57 +00:00
|
|
|
func ToMap(v any) (*linkedhashmap.Map[string, any], 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-02 19:42:57 +00:00
|
|
|
var content linkedhashmap.Map[string, any]
|
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-02 19:42:57 +00:00
|
|
|
func MergeObjects(objects ...any) (*linkedhashmap.Map[string, any], error) {
|
|
|
|
var content linkedhashmap.Map[string, any]
|
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) {
|
|
|
|
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
|
|
|
|
}
|
|
|
|
var content linkedhashmap.Map[string, any]
|
|
|
|
err = content.UnmarshalJSON(inputContent)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
content.RemoveAll(parentContent.Keys())
|
|
|
|
inputContent, err = content.MarshalJSON()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
decoder := json.NewDecoder(bytes.NewReader(inputContent))
|
|
|
|
decoder.DisallowUnknownFields()
|
|
|
|
return decoder.Decode(object)
|
2022-07-02 17:57:04 +00:00
|
|
|
}
|