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

     1  package json
     2  
     3  import (
     4  	"bytes"
     5  	"strings"
     6  
     7  	"github.com/sagernet/sing/common"
     8  	E "github.com/sagernet/sing/common/exceptions"
     9  )
    10  
    11  func UnmarshalExtended[T any](content []byte) (T, error) {
    12  	decoder := NewDecoder(NewCommentFilter(bytes.NewReader(content)))
    13  	var value T
    14  	err := decoder.Decode(&value)
    15  	if err == nil {
    16  		return value, err
    17  	}
    18  	if syntaxError, isSyntaxError := err.(*SyntaxError); isSyntaxError {
    19  		prefix := string(content[:syntaxError.Offset])
    20  		row := strings.Count(prefix, "\n") + 1
    21  		column := len(prefix) - strings.LastIndex(prefix, "\n") - 1
    22  		return common.DefaultValue[T](), E.Extend(syntaxError, "row ", row, ", column ", column)
    23  	}
    24  	return common.DefaultValue[T](), err
    25  }