Skip to content

Commit

Permalink
Merge pull request hashicorp#174 from kron4eg/decode-int
Browse files Browse the repository at this point in the history
Try to use SetInt in case if possible
  • Loading branch information
mitchellh committed Dec 1, 2016
2 parents ae25c98 + e6cd87d commit 37ab263
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
14 changes: 11 additions & 3 deletions decoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -164,15 +164,23 @@ 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)
if err != nil {
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
}
}
Expand Down
16 changes: 16 additions & 0 deletions decoder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"path/filepath"
"reflect"
"testing"
"time"

"github.com/davecgh/go-spew/spew"
"github.com/hashicorp/hcl/hcl/ast"
Expand Down Expand Up @@ -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 {
Expand Down

0 comments on commit 37ab263

Please sign in to comment.