2022-07-03 11:43:27 +00:00
|
|
|
package badjson
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2022-07-26 05:53:25 +00:00
|
|
|
"reflect"
|
2022-07-03 11:43:27 +00:00
|
|
|
|
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"
|
|
|
|
)
|
|
|
|
|
|
|
|
type JSONArray[T any] []T
|
|
|
|
|
|
|
|
func (a JSONArray[T]) MarshalJSON() ([]byte, error) {
|
|
|
|
return json.Marshal([]T(a))
|
|
|
|
}
|
|
|
|
|
|
|
|
func (a *JSONArray[T]) UnmarshalJSON(content []byte) error {
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
|
|
|
func (a *JSONArray[T]) decodeJSON(decoder *json.Decoder) error {
|
|
|
|
for decoder.More() {
|
2022-07-26 05:53:25 +00:00
|
|
|
value, err := decodeJSON(decoder)
|
2022-07-03 11:43:27 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-07-26 05:53:25 +00:00
|
|
|
item, ok := value.(T)
|
|
|
|
if !ok {
|
|
|
|
var defValue T
|
|
|
|
return E.New("can't cast ", value, " to ", reflect.TypeOf(defValue))
|
|
|
|
}
|
2022-07-04 07:34:43 +00:00
|
|
|
*a = append(*a, item)
|
2022-07-03 11:43:27 +00:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|