badjson: Add UnmarshalExtended

This commit is contained in:
世界 2023-12-12 20:13:52 +08:00
parent 56b953e091
commit edd320c3a8
No known key found for this signature in database
GPG key ID: CD109927C34A63C4

25
common/json/unmarshal.go Normal file
View file

@ -0,0 +1,25 @@
package json
import (
"bytes"
"strings"
"github.com/sagernet/sing/common"
E "github.com/sagernet/sing/common/exceptions"
)
func UnmarshalExtended[T any](content []byte) (T, error) {
decoder := NewDecoder(NewCommentFilter(bytes.NewReader(content)))
var value T
err := decoder.Decode(&value)
if err == nil {
return value, err
}
if syntaxError, isSyntaxError := err.(*SyntaxError); isSyntaxError {
prefix := string(content[:syntaxError.Offset])
row := strings.Count(prefix, "\n") + 1
column := len(prefix) - strings.LastIndex(prefix, "\n") - 1
return common.DefaultValue[T](), E.Extend(syntaxError, "row ", row, ", column ", column)
}
return common.DefaultValue[T](), err
}