summaryrefslogtreecommitdiff
path: root/decode.go
diff options
context:
space:
mode:
authorLuke Shumaker <lukeshu@datawire.io>2022-08-16 21:50:07 -0600
committerLuke Shumaker <lukeshu@datawire.io>2022-08-17 00:34:48 -0600
commit111cdaffb625f7db9b8c5a27e386999944346e0d (patch)
treecdb6493361b4343cd2cb05ef76b77cfc5a682a1b /decode.go
parent0e6d82b97165e9cdd294aaeac02bbbf26263877a (diff)
Fix those now-failing error checks
Diffstat (limited to 'decode.go')
-rw-r--r--decode.go29
1 files changed, 29 insertions, 0 deletions
diff --git a/decode.go b/decode.go
index a17a572..52fcb5e 100644
--- a/decode.go
+++ b/decode.go
@@ -121,6 +121,26 @@ func Decode(r interface {
return NewDecoder(r).Decode(ptr)
}
+// DecodeThenEOF is like decode, but emits an error if there is extra data after the JSON.
+func DecodeThenEOF(r interface {
+ io.Reader
+ io.RuneScanner
+}, ptr any) error {
+ dec := NewDecoder(r)
+ if err := dec.Decode(ptr); err != nil {
+ return err
+ }
+ if c, _, err := r.ReadRune(); err == nil {
+ return &DecodeError{
+ Err: &DecodeSyntaxError{
+ Err: fmt.Errorf("invalid character %q after top-level value", c),
+ Offset: dec.InputOffset(),
+ },
+ }
+ }
+ return nil
+}
+
func (dec *Decoder) Decode(ptr any) (err error) {
ptrVal := reflect.ValueOf(ptr)
if ptrVal.Kind() != reflect.Pointer || ptrVal.IsNil() || !ptrVal.Elem().CanSet() {
@@ -147,6 +167,15 @@ func (dec *Decoder) Decode(ptr any) (err error) {
}
}()
dec.decode(ptrVal.Elem(), false)
+ for {
+ _, s, t, _ := dec.io.ReadRuneType()
+ if t == RuneTypeEOF || t == RuneTypeError {
+ if s > 0 {
+ dec.io.UnreadRune()
+ }
+ break
+ }
+ }
return nil
}