Skip to content

Commit

Permalink
badjson: Add UnmarshalExtended
Browse files Browse the repository at this point in the history
  • Loading branch information
nekohasekai committed Dec 14, 2023
1 parent 35e7014 commit bf06c45
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions common/json/unmarshal.go
Original file line number Diff line number Diff line change
@@ -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
}

0 comments on commit bf06c45

Please sign in to comment.