Skip to content

Commit 3b2de25

Browse files
committed
fix(decoder): Correctly unmarshal !!int tagged values
1 parent 25e5d90 commit 3b2de25

File tree

2 files changed

+58
-5
lines changed

2 files changed

+58
-5
lines changed

decode.go

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,36 @@ func (d *Decoder) isExceededMaxDepth() bool {
8181
return d.decodeDepth > maxDecodeDepth
8282
}
8383

84+
func (d *Decoder) castToInt(v interface{}) interface{} {
85+
switch vv := v.(type) {
86+
case int:
87+
return int64(vv)
88+
case int8:
89+
return int64(vv)
90+
case int16:
91+
return int64(vv)
92+
case int32:
93+
return int64(vv)
94+
case int64:
95+
return vv
96+
case uint:
97+
return uint64(vv)
98+
case uint8:
99+
return uint64(vv)
100+
case uint16:
101+
return uint64(vv)
102+
case uint32:
103+
return uint64(vv)
104+
case uint64:
105+
return vv
106+
case string:
107+
// if error occurred, return zero value
108+
i, _ := strconv.ParseInt(vv, 10, 64)
109+
return i
110+
}
111+
return 0
112+
}
113+
84114
func (d *Decoder) castToFloat(v interface{}) interface{} {
85115
switch vv := v.(type) {
86116
case int:
@@ -382,8 +412,7 @@ func (d *Decoder) nodeToValue(ctx context.Context, node ast.Node) (any, error) {
382412
if err != nil {
383413
return nil, err
384414
}
385-
i, _ := strconv.Atoi(fmt.Sprint(v))
386-
return i, nil
415+
return d.castToInt(v), nil
387416
case token.FloatTag:
388417
v, err := d.nodeToValue(ctx, n.Value)
389418
if err != nil {

decode_test.go

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -586,17 +586,41 @@ func TestDecoder(t *testing.T) {
586586
},
587587

588588
// Explicit tags.
589+
{
590+
source: "v: !!int 'not-an-int'",
591+
value: map[string]int{"v": 0},
592+
},
593+
{
594+
source: "v: !!int '000'",
595+
value: map[string]int{"v": 0},
596+
},
597+
{
598+
source: "v: !!int '007'",
599+
value: map[string]int{"v": 7},
600+
},
601+
{
602+
source: "v: !!int '-007'",
603+
value: map[string]int{"v": -7},
604+
},
605+
{
606+
source: "v: !!int 0xff",
607+
value: map[string]int{"v": 255},
608+
},
609+
{
610+
source: "v: !!int 0o10",
611+
value: map[string]int{"v": 8},
612+
},
589613
{
590614
source: "v: !!float '1.1'",
591-
value: map[string]interface{}{"v": 1.1},
615+
value: map[string]float64{"v": 1.1},
592616
},
593617
{
594618
source: "v: !!float 0",
595-
value: map[string]interface{}{"v": float64(0)},
619+
value: map[string]float64{"v": 0},
596620
},
597621
{
598622
source: "v: !!float -1",
599-
value: map[string]interface{}{"v": float64(-1)},
623+
value: map[string]float64{"v": -1},
600624
},
601625
{
602626
source: "v: !!null ''",

0 commit comments

Comments
 (0)