sing-box/common/badjson/object.go

80 lines
1.8 KiB
Go
Raw Permalink Normal View History

2022-07-03 11:43:27 +00:00
package badjson
import (
"bytes"
"strings"
2022-07-24 09:58:52 +00:00
"github.com/sagernet/sing-box/common/json"
2022-07-03 11:43:27 +00:00
E "github.com/sagernet/sing/common/exceptions"
"github.com/sagernet/sing/common/x/linkedhashmap"
)
type JSONObject struct {
linkedhashmap.Map[string, any]
}
2022-08-11 04:41:54 +00:00
func (m JSONObject) MarshalJSON() ([]byte, error) {
2022-07-03 11:43:27 +00:00
buffer := new(bytes.Buffer)
buffer.WriteString("{")
items := m.Entries()
iLen := len(items)
for i, entry := range items {
keyContent, err := json.Marshal(entry.Key)
if err != nil {
return nil, err
}
buffer.WriteString(strings.TrimSpace(string(keyContent)))
buffer.WriteString(": ")
valueContent, err := json.Marshal(entry.Value)
if err != nil {
return nil, err
}
buffer.WriteString(strings.TrimSpace(string(valueContent)))
if i < iLen-1 {
buffer.WriteString(", ")
}
}
buffer.WriteString("}")
return buffer.Bytes(), nil
}
func (m *JSONObject) UnmarshalJSON(content []byte) error {
decoder := json.NewDecoder(bytes.NewReader(content))
m.Clear()
objectStart, err := decoder.Token()
if err != nil {
return err
} else if objectStart != json.Delim('{') {
return E.New("expected json object start, but starts with ", objectStart)
}
err = m.decodeJSON(decoder)
if err != nil {
2022-07-26 05:53:25 +00:00
return E.Cause(err, "decode json object content")
2022-07-03 11:43:27 +00:00
}
objectEnd, err := decoder.Token()
if err != nil {
return err
} else if objectEnd != json.Delim('}') {
return E.New("expected json object end, but ends with ", objectEnd)
}
return nil
}
func (m *JSONObject) decodeJSON(decoder *json.Decoder) error {
for decoder.More() {
var entryKey string
2022-07-26 05:53:25 +00:00
keyToken, err := decoder.Token()
2022-07-03 11:43:27 +00:00
if err != nil {
return err
}
2022-07-26 05:53:25 +00:00
entryKey = keyToken.(string)
2022-07-03 11:43:27 +00:00
var entryValue any
entryValue, err = decodeJSON(decoder)
if err != nil {
2022-07-26 05:53:25 +00:00
return E.Cause(err, "decode value for ", entryKey)
2022-07-03 11:43:27 +00:00
}
m.Put(entryKey, entryValue)
}
return nil
}