github.com/sagernet/sing@v0.4.0-beta.19.0.20240518125136-f67a0988a636/common/json/badjson/array.go (about)

     1  package badjson
     2  
     3  import (
     4  	"bytes"
     5  
     6  	"github.com/sagernet/sing/common"
     7  	E "github.com/sagernet/sing/common/exceptions"
     8  	"github.com/sagernet/sing/common/json"
     9  )
    10  
    11  type JSONArray []any
    12  
    13  func (a JSONArray) IsEmpty() bool {
    14  	if len(a) == 0 {
    15  		return true
    16  	}
    17  	return common.All(a, func(it any) bool {
    18  		if valueInterface, valueMaybeEmpty := it.(isEmpty); valueMaybeEmpty && valueInterface.IsEmpty() {
    19  			return true
    20  		}
    21  		return false
    22  	})
    23  }
    24  
    25  func (a JSONArray) MarshalJSON() ([]byte, error) {
    26  	return json.Marshal([]any(a))
    27  }
    28  
    29  func (a *JSONArray) UnmarshalJSON(content []byte) error {
    30  	decoder := json.NewDecoder(bytes.NewReader(content))
    31  	arrayStart, err := decoder.Token()
    32  	if err != nil {
    33  		return err
    34  	} else if arrayStart != json.Delim('[') {
    35  		return E.New("excepted array start, but got ", arrayStart)
    36  	}
    37  	err = a.decodeJSON(decoder)
    38  	if err != nil {
    39  		return err
    40  	}
    41  	arrayEnd, err := decoder.Token()
    42  	if err != nil {
    43  		return err
    44  	} else if arrayEnd != json.Delim(']') {
    45  		return E.New("excepted array end, but got ", arrayEnd)
    46  	}
    47  	return nil
    48  }
    49  
    50  func (a *JSONArray) decodeJSON(decoder *json.Decoder) error {
    51  	for decoder.More() {
    52  		item, err := decodeJSON(decoder)
    53  		if err != nil {
    54  			return err
    55  		}
    56  		*a = append(*a, item)
    57  	}
    58  	return nil
    59  }