sing-box/common/badjson/array.go

47 lines
961 B
Go
Raw Normal View History

2022-07-03 11:43:27 +00:00
package badjson
import (
"bytes"
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"
)
2022-07-27 13:57:21 +00:00
type JSONArray []any
2022-07-03 11:43:27 +00:00
2022-07-27 13:57:21 +00:00
func (a JSONArray) MarshalJSON() ([]byte, error) {
return json.Marshal([]any(a))
2022-07-03 11:43:27 +00:00
}
2022-07-27 13:57:21 +00:00
func (a *JSONArray) UnmarshalJSON(content []byte) error {
2022-07-03 11:43:27 +00:00
decoder := json.NewDecoder(bytes.NewReader(content))
arrayStart, err := decoder.Token()
if err != nil {
return err
} else if arrayStart != json.Delim('[') {
return E.New("excepted array start, but got ", arrayStart)
}
err = a.decodeJSON(decoder)
if err != nil {
return err
}
arrayEnd, err := decoder.Token()
if err != nil {
return err
} else if arrayEnd != json.Delim(']') {
return E.New("excepted array end, but got ", arrayEnd)
}
return nil
}
2022-07-27 13:57:21 +00:00
func (a *JSONArray) decodeJSON(decoder *json.Decoder) error {
2022-07-03 11:43:27 +00:00
for decoder.More() {
2022-07-27 13:57:21 +00:00
item, err := decodeJSON(decoder)
2022-07-03 11:43:27 +00:00
if err != nil {
return err
}
2022-07-04 07:34:43 +00:00
*a = append(*a, item)
2022-07-03 11:43:27 +00:00
}
return nil
}