Try to use SetInt in case if possible

Allows to decode aliased int types, like time.Duration
This commit is contained in:
Artiom Diomin 2016-12-01 16:14:15 +02:00
parent ae25c981c1
commit e6cd87d208
2 changed files with 27 additions and 3 deletions

View File

@ -91,7 +91,7 @@ func (d *decoder) decode(name string, node ast.Node, result reflect.Value) error
return d.decodeBool(name, node, result)
case reflect.Float64:
return d.decodeFloat(name, node, result)
case reflect.Int:
case reflect.Int, reflect.Int32, reflect.Int64:
return d.decodeInt(name, node, result)
case reflect.Interface:
// When we see an interface, we make our own thing
@ -164,7 +164,11 @@ func (d *decoder) decodeInt(name string, node ast.Node, result reflect.Value) er
return err
}
result.Set(reflect.ValueOf(int(v)))
if result.Kind() == reflect.Interface {
result.Set(reflect.ValueOf(int(v)))
} else {
result.SetInt(v)
}
return nil
case token.STRING:
v, err := strconv.ParseInt(n.Token.Value().(string), 0, 0)
@ -172,7 +176,11 @@ func (d *decoder) decodeInt(name string, node ast.Node, result reflect.Value) er
return err
}
result.Set(reflect.ValueOf(int(v)))
if result.Kind() == reflect.Interface {
result.Set(reflect.ValueOf(int(v)))
} else {
result.SetInt(v)
}
return nil
}
}

View File

@ -5,6 +5,7 @@ import (
"path/filepath"
"reflect"
"testing"
"time"
"github.com/davecgh/go-spew/spew"
"github.com/hashicorp/hcl/hcl/ast"
@ -781,6 +782,21 @@ func TestDecode_intString(t *testing.T) {
}
}
func TestDecode_intStringAliased(t *testing.T) {
var value struct {
Count time.Duration
}
err := Decode(&value, testReadFile(t, "basic_int_string.hcl"))
if err != nil {
t.Fatalf("err: %s", err)
}
if value.Count != time.Duration(3) {
t.Fatalf("bad: %#v", value.Count)
}
}
func TestDecode_Node(t *testing.T) {
// given
var value struct {