From edd320c3a8be91cb59b8bbcee6ef2c0ea5921a17 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=96=E7=95=8C?= Date: Tue, 12 Dec 2023 20:13:52 +0800 Subject: [PATCH] badjson: Add UnmarshalExtended --- common/json/unmarshal.go | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 common/json/unmarshal.go diff --git a/common/json/unmarshal.go b/common/json/unmarshal.go new file mode 100644 index 0000000..fa6452d --- /dev/null +++ b/common/json/unmarshal.go @@ -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 +}