Skip to content

Commit

Permalink
Try to use SetInt in case if possible
Browse files Browse the repository at this point in the history
Allows to decode aliased int types, like time.Duration
  • Loading branch information
kron4eg committed Dec 1, 2016
1 parent ae25c98 commit e6cd87d
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 e6cd87d

Please sign in to comment.